Servers and environment
Node, the difference between development and production
Set up different configurations for development and production in Node.js with the NODE_ENV environment variable, with an Express example.
You can have different configurations for production and development environments.
Node assumes it’s always running in a development environment.
You can signal Node.js that you are running in production by setting the NODE_ENV=production environment variable.
This is usually done by executing the command
export NODE_ENV=production
in the shell, but it’s better to put it in your shell configuration file (e.g. .bash_profile with the Bash shell) because otherwise the setting does not persist in case of a system restart.
You can also apply the environment variable by prepending it to your application initialization command:
NODE_ENV=production node app.js
Run that and check the value:
console.log(process.env.NODE_ENV) // 'production'
This environment variable is a convention that is widely used in external libraries as well.
Setting the environment to production generally ensures that
- logging is kept to a minimum, essential level
- more caching levels take place to optimize performance
For example Pug, the templating library used by Express, compiles in debug mode if NODE_ENV is not set to production. Express views are compiled in every request in development mode, while in production they are cached. There are many more examples.
Older Express versions had app.configure('production', …) hooks that ran based on NODE_ENV. Express 4 removed them. Today you branch on process.env.NODE_ENV yourself. A common case is the error handler: verbose with a stack trace while developing, terse in production so you never leak internals to users:
const isDev = process.env.NODE_ENV !== 'production'
app.use((err, req, res, next) => {
console.error(err)
res.status(500).json(
isDev ? { error: err.message, stack: err.stack } : { error: 'Internal error' }
)
})
Run it with NODE_ENV=production node app.js, trigger an error, and the JSON body only says Internal error. Run it without the variable and you get the message and the full stack.
My advice is to set NODE_ENV=production in your deployment platform’s environment settings rather than hardcoding it in source. That way local development stays verbose and production stays fast.
Lesson completed