Javascript Disable console.log on Production Environment

Both on Node & Frontend apps

In JavaScript applications, especially on Frontend apps, we might want to disable our console.logs that are placed for debugging. Below are the two possible ways to do it:

1. Better Approach

Let’s create a helper.js file that exports a log method.

const log = (function (environment) {
  if (environment === "production") {
    return () => { }
  }
  return (...args) => {
    console.log(...args)
  }
})(process.env.NODE_ENV);


export {
  log
}

The above logic explained:

  • We export the named method log, which is an IIFE (Immediately Invoked Function Expression).

  • To IIFE we pass an environment variable. In the above example, process.env.NODE_ENV is what we would pass in case of React application (built with Create React App). For Node, Express and other applications such as in Vue or Angular, their respective environment checks should be passed.

  • In the IIFE, we check if the environment is production or not. If production, we return an empty function that would print nothing. If not production, we return a method that would pass on all the arguments to console.log as it is (notice the use of rest parameter and spread syntax.)

To use, simply import and call.

import { log } from "./helper.js";

log("Hello", 1, 2, 3, Date.now());

2. Simpler But Drastic Way

It’s usually never a good idea to modify a globally available function, but if you have your reasons and you do not want to log anything in production environment (or based on any other check), you can simply replace console.log method with an empty function that does nothing. In Node or Frontend app, this should be placed in the file where the application starts from.

if (process.env.NODE_ENV === "production") {
  console.log = () => { };
}

Now throughout the application in production environment console.log() calls will print nothing. For all other environments, the usual console.log will work as expected.


The above two approaches are equally applicable to other console methods such as console.error, console.debug, console.table, console.warn etc.

See also