How often do you log your messages to dev tools to debug or study the shape of your payload? Have you adopted an existing codebase logging incessant console messages?
Logging messages is an important skill during development but a huge mistake when shipping your code to production. It exposes sensitive information to the entire internet. Is there a magic wand tool for disabling console messages? Yes, there is.
Understanding console
Console is an object that exists inside the window (a window is itself an object that holds the native code that runs the whole browser tab). It has 25 utility methods (functions declared inside a JavaScript object), including the popular log(), error(), info(), and table(). Go ahead, open developer tools and enter window.console.
Disabling Console
"Monkey patching" is a term used in software engineering when manipulating native code to suit the user's needs, such as adding an object to window or overwriting existing code.
To disable console methods, identify the method you want to disable and then assign it an empty JavaScript function.
For our case we want to disable the console. log() method.
console.log=()=>{}
Please ensure you put this logic at the root of your application, the entry point of JavaScript parser, first line that JavaScript begins with.
Only disable it in production
Console messages are useful during development but not in production. To disable in production there 2 ways:
- Node js initialized projects
if(process.NODE_ENV ==="production"){ console.log=()=>{}}
- Detecting the domain
if(location.origin.includes("mydomain")){console.log=()=>{}}
Caution
Monkey patching is highly frowned upon in software engineering world; be careful when overwriting console messages, especially the error() method as it can help spot production errors.
Top comments (0)