Production Tips
Final checklist for running a fast, reliable Express app in production.
Before you go live, review these essentials:
- Set
NODE_ENV=productionfor better performance and safer errors. - Use a process manager like pm2 to restart the app on crashes and run multiple instances.
- Enable
compression()middleware to gzip responses. - Log to a service and monitor errors and uptime.
- Serve over HTTPS, usually terminated at the proxy.
- Handle graceful shutdown so in-flight requests finish.
Example
const compression = require('compression');
app.use(compression());
process.on('SIGTERM', () => {
console.log('Shutting down gracefully');
server.close(() => process.exit(0));
});
const server = app.listen(process.env.PORT || 3000);When to use it
- A team sets NODE_ENV=production so Express disables template caching warnings, enables gzip compression, and libraries use production optimisations.
- A developer adds the compression middleware so the Express app gzip-compresses JSON responses, reducing bandwidth by up to 70%.
- A production checklist item ensures that all unhandled promise rejections are caught at the process level to prevent silent failures.
More examples
Enable gzip compression
Registers the compression middleware before routes so all JSON and HTML responses are gzip-compressed automatically.
const express = require('express');
const compression = require('compression');
const app = express();
app.use(compression()); // must come before routes
app.get('/data', (req, res) => {
res.json({ items: Array(1000).fill({ id: 1 }) });
});
app.listen(3000);Catch unhandled rejections
Attaches process-level handlers to log and exit on any uncaught error or unhandled promise rejection in production.
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
process.exit(1);
});
process.on('unhandledRejection', (reason) => {
console.error('Unhandled Rejection:', reason);
process.exit(1);
});
const app = require('./app');
app.listen(process.env.PORT || 3000);PM2 ecosystem config
A PM2 ecosystem file that runs the Express server in cluster mode across all CPU cores with production env vars.
// ecosystem.config.js
module.exports = {
apps: [{
name: 'my-api',
script: 'server.js',
instances: 'max',
exec_mode: 'cluster',
env: { NODE_ENV: 'development' },
env_production: { NODE_ENV: 'production', PORT: 3000 },
}],
};
Discussion