7 March, 20251 minute read

Strip `console.log`s from a Next.js project

Throwing in a console.log statement is a nice and easy way to quickly print debug your way to the bottom of an issue, but a common problem is that engineers often forget to clean them up and the leftovers can easily slip through code review. Judicious self review of your work can help catch these stragglers, but it is not a foolproof method.

Some teams resort to configuring ESLint so that a console.log call fails CI, but I tend to be of the opinion that this is not a great use of time. It feels wasteful to trigger another CI run just to fix a problem as simple as this, and the leftover logs typically don't really hurt anyone. Besides, if tooling can detect the presence of these statements and fail the build then surely tooling can also just remove them?

It turns out that Next.js has an option you can enable to do exactly that. Setting the compiler.removeConsole option in your configuration file will remove all console statements as part of the build process without any need for manual intervention. Because Next.js' configuration file is code, you can also very easily opt in to this behavior only for your production builds:

Click to copy
import type { NextConfig } from 'next'; const nextConfig: NextConfig = {  // ...  compiler: {    removeConsole: process.env.NODE_ENV === 'production',  },}; export default nextConfig;

And if you—for some reason—want to preserve certain log levels, you can configure that as well:

Click to copy
 import type { NextConfig } from 'next'; const nextConfig: NextConfig = {  // ...  compiler: {    removeConsole:      process.env.NODE_ENV === 'production'        ? { exclude: ['warn', 'error'] }        : false,  },}; export default nextConfig;

Don't want to miss out on new posts?

Join 100+ fellow engineers who subscribe for software insights, technical deep-dives, and valuable advice.

Get in touch 👋

If you're working on an innovative web or AI software product, then I'd love to hear about it. If we both see value in working together, we can move forward. And if not—we both had a nice chat and have a new connection.
Send me an email at hello@sophiabits.com