Say Goodbye to console.log from Production environment
Gulshan Aggarwal

Gulshan Aggarwal @gulshanaggarwal

About: Software Engineer @Zura Ventures

Location:
Alwar
Joined:
Jul 4, 2020

Say Goodbye to console.log from Production environment

Publish Date: Jun 24 '22
261 66

I have been working on a project with Next.js since last month and used the console.log statement in lots of components & files even though I don't remember. Usually, we use it to check API responses and some other areas of the application.

Making console statements public is not a good idea at all, it may bring your app at a security risk. Checking every file, and deleting the statement is very time-consuming & boring too. As a developer, we all hate boring tasks so, in the article here we discuss how you can say goodbye to console.log in your Next.js app from the Production environment in just less than 1 minute.

sounds good

Sounds good! let's goooo...😎

👉 Follow the steps mentioned below -

1. Install the babel-plugin-transform-remove-console package as a development dependency.

2. Create a .babelrc file at the root of your project, copy the below content & that's all.



{
    "presets": [
        "next/babel"
    ],
    "env": {
        "production": {
            "plugins": [
                "transform-remove-console"
            ]
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

🏁 This is just a short trick that I used to enhance my productivity, even you should use it next time.
I will keep sharing more tips & tricks related to web dev,stay tuned!.

Thanks for reading.

goodbye

Comments 66 total

  • snowlyg
    snowlygJun 24, 2022

    nice

  • Sakshi
    SakshiJun 24, 2022

    helpful

  • Gulshan Aggarwal
    Gulshan AggarwalJun 24, 2022

    Thanks, Clary! I will keep posting cool & knowledgeable content.

  • Mirko Sedda
    Mirko SeddaJun 24, 2022

    Hi! Why console.logs are a security risk?

    • Gulshan Aggarwal
      Gulshan AggarwalJun 24, 2022

      Hey, Mirko! thanks for asking the question. Sometimes you need to console your environment variable values to check why it's undefined or not working, this may cause your credentials at risk.

      • Danny Engelman
        Danny EngelmanJun 24, 2022

        Great, now we can label all SSR code as a 'security risk'

        • Gulshan Aggarwal
          Gulshan AggarwalJun 24, 2022

          Hey, I didn't mean that

          • Danny Engelman
            Danny EngelmanJun 25, 2022

            But you said so.

            console.log can log everything the user can access in the Inspector.

            console.log can only print unwanted credentials when the back-end provided them, there for you imply everything coming from the back-end is a security risk.

            Or saying console.log is a security risk is just stupid.

            • Gulshan Aggarwal
              Gulshan AggarwalJun 25, 2022

              I strongly disagree. I didn't mean that at all. Here I just mentioned a situation ,how a user can put his/her credentials on risk.

      • Mirko Sedda
        Mirko SeddaJun 24, 2022

        Interesting 😊 thats the only thing that always worked for me 😂

    • Jeff
      JeffJun 25, 2022

      Maybe for performance reasons? Like it runs on the main thread in the browser...

  • greenchapeljohn
    greenchapeljohnJun 24, 2022

    That’s nice and simple on Next.js.
    On Angular I created a service for logging and the log level is set based on what environment you log too. I then like to use the linter to stop any uses of console.log in the code ( except in the service ) a good git hook running the lint then stops people from committing a console log in the code.

    One advantage I get with this is based on the error the service can decide if it wants to send the log via REST API to an external service for monitoring.

    • Gulshan Aggarwal
      Gulshan AggarwalJun 24, 2022

      Oh! making something cool is very hard but you did it, hats off you man.

    • Ron Jonk
      Ron JonkJun 25, 2022

      And then y can check a session variable to either show or hide the logs on production is also possible. It will be very difficult in your minified code to find that needed session variable to set the log.level. Show default the loglevel “error” and not “ debug” and with the session variable set y can show all “debug” level logs

  • 🚩 Atul Prajapati 🇮🇳
    🚩 Atul Prajapati 🇮🇳Jun 24, 2022

    That's amazing

  • MilMike
    MilMikeJun 24, 2022

    I do this too but without a plugin, I simply set an empty function for console.log on prod env.

    console.log = function(){}
    
    Enter fullscreen mode Exit fullscreen mode

    beside console sometimes people also use alert to test something. In some of our webapps we disabled alert the same way like above.. (someone once pushed alert("curse word") on friday in production, it popped up when user did something special. We got interesting mails on monday... ;)

    • Gulshan Aggarwal
      Gulshan AggarwalJun 24, 2022

      nice! approach I'm gonna try it next time 👌

    • Jeff
      JeffJun 25, 2022

      What about?

      globalThis.console = { log: () => {} };

      • Hyerim
        HyerimJun 25, 2022

        Wow Im newbie and wanna know how I can use this.
        type just like normal console.log()?

      • Eduardo Cuomo
        Eduardo CuomoJun 26, 2022

        What will happen when I use console.info() for example?

        • Jeff
          JeffJun 26, 2022

          Calling info() will cause an exception.

          So a better approach would be to do the following if you are only interested in silencing console.log:

          globalThis.console.log = () => {};
          
          Enter fullscreen mode Exit fullscreen mode

          It's helpful you called this out.

    • Peter Vivo
      Peter VivoJun 25, 2022

      consol.log harming by the way when client assign her own function to grab information

      window.console.log = grabLogEntries
      
      Enter fullscreen mode Exit fullscreen mode

      with overwrite our cleaning in client side.

    • lionel-rowe
      lionel-roweJun 25, 2022

      That's annoying as hell for anyone developing downstream code (browser extensions etc.) to be compatible with your site/web app. Much better to use lint rules or an approach like the one mentioned in this article.

    • Etienne-Joseph Charles
      Etienne-Joseph CharlesJun 30, 2022

      Just curiously, wouldn't that that prevent from errors beings logged if ever you're using something like Sentry or DataDog or NewRelic to log errors ?

  • Muhammad Uzair
    Muhammad UzairJun 24, 2022

    That's nice trick, but It won't pass code review.

  • Jared Long
    Jared Long Jun 25, 2022

    Could even use husky to setup custom git hooks for blocking a push or commit if linting fails

    • Gulshan Aggarwal
      Gulshan AggarwalJun 25, 2022

      Nice trick! but what if you setup the rule late for you console.log ?

  • Gulshan Aggarwal
    Gulshan AggarwalJun 25, 2022

    Nice trick! but what if you setup the rule late for you console.log ?

    • Jared Long
      Jared Long Jun 25, 2022

      Eslint-nibble is also an amazing tool for visualizing linting categories & errors in the project. It should also be able to auto remove all console.logs

  • Gulshan Aggarwal
    Gulshan AggarwalJun 25, 2022

    It means ESLint will autofix console.log from all files?

  • Gulshan Aggarwal
    Gulshan AggarwalJun 25, 2022

    I couldn't find something that's the reason I tried it but now lots of solutions are available in comments.

  • Gulshan Aggarwal
    Gulshan AggarwalJun 25, 2022

    Next time, I'm gonna surely try all these suggestions but this time I will continue it.

  • Ayyash
    AyyashJun 25, 2022

    you don't need a plugin, you can wrap it yourself: dev.to/ayyash/writing-a-wrapper-fo...

  • nicoatridge
    nicoatridgeJun 25, 2022

    I just add this code:
    let testMode = true; // console log suppressed if false
    if (!testMode) {console.log = function() {};} // to suppress console log

  • Pixeliner
    PixelinerJun 25, 2022

    console.logs should just be used to bug check and afterwards removed. Don't leave it in the source code, especially not in big companies. You can maybe create a peek functionality in your utils, but that's that. Using build tools to remove code is just bad practice.

    • Gulshan Aggarwal
      Gulshan AggarwalJun 25, 2022

      True 💯 but what do you mean by build tools to remove code ?

  • Abdur Rehman Khalid
    Abdur Rehman KhalidJun 25, 2022

    Some may be thinking that why we are not allowed to use the console.log in the production plus some other development enviornemnt as well, so the answer is that if you are fetching a lot of data from Back-End and printing that data in the Front-End in any framework then it is quite possible that, that data will again some time to get printed at the console so due to this reason we should avoid printing direct data to the console.

    The other thing that has been mentioned in this article is the security risk, this also put the application on the risk as well.

    This plugin looks good but it is there is a need to communicate the need and usage of this plugin to the other members of the team as well. However, I appreciate that you have bring this matter of writing console log on the production deployed application. This is a critical thing to which only a few developers pay attention, more power to you and looking forward to see some important articles from your side. Good Luck.

    • Gulshan Aggarwal
      Gulshan AggarwalJun 25, 2022

      Thanks for the detailed explanation & lovey wishes! 🤗

  • Jakob Attkinson
    Jakob AttkinsonJun 26, 2022

    How about an ESLint rule for no console and a pre-commit hook?

    This way, you don't need any ninja-hacks. You do your testing and remove them before the commit.

  • Andrew Baisden
    Andrew BaisdenJun 26, 2022

    Linting rules seem like a great solution for this.

  • dikamilo
    dikamiloJun 27, 2022

    I prefer to create a custom logger wrapper/class and use it in app. In react apps as custom context/provider with hook to get logger instance in components.

    Why? Several advantages:

    • log to multiple services, not just console if necessary
    • different logger implementation for tests, you can mock logger methods and assert them in tests (if you have business flow logs, then this is useful)
    • different logger implementation for storybook: you can see logs as actions in storybook
    • production? Just use dummy logger that do nothing or log only to production services

    "Checking every file, and deleting the statement is very time-consuming"
    ESLint's rule to deny console logs + ignore them just in console logger implementation

    • Gulshan Aggarwal
      Gulshan AggarwalJun 27, 2022

      Actually, while searching for the solution I had no idea about logger services so I solved it using the package. Yeah! thanks for the detailed solution ♥

  • littleTreeme
    littleTreemeJun 28, 2022

    hi,your article is so good! Can I translate your artical and post to my wechat public account?

Add comment