Learn how to optimize your Node.js application for production by setting up different configurations for development and production environments.
Node.js is designed to assume that it is always running in a development environment. However, when deploying your application to production, it is important to signal to Node.js that it is running in a production environment. This can be done by setting the NODE_ENV=production
environment variable.
To set this variable, you can execute the following command in the shell:
export NODE_ENV=production
It is recommended to add this command to your shell configuration file (e.g., .bash_profile
for Bash shell) to ensure that the setting persists even after a system restart.
Alternatively, you can prepend the environment variable to your application initialization command:
NODE_ENV=production node app.js
The NODE_ENV=production
convention is widely used in external libraries as well.
Setting the environment to production
has several benefits, including:
-
Optimized Logging: Logging is kept to a minimum, essential level, reducing the overhead associated with logging in a development environment.
-
Improved Performance: More caching levels are implemented to optimize performance. For example, libraries like Pug (used by Express) compile in debug mode when
NODE_ENV
is not set toproduction
. In development mode, Express views are compiled for every request, while in production mode, they are cached for better performance.
Express provides configuration hooks that are automatically called based on the value of the NODE_ENV
variable. For example, you can use these hooks to set different error handlers for different environments:
app.configure('development', () => {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', () => {
app.use(express.errorHandler());
});
By utilizing these configuration hooks, you can customize your application behavior based on the environment it is running in.
Tags: Node.js, development, production, environment variables, optimization, performance optimization, configuration hooks, error handling