Setting up your Node.js app for production is like preparing for a long road trip. You need to pack the essentials, tune up your engine, and make sure nothing breaks along the way. In this guide, we’ll cover how to properly configure environment variables and settings for a smooth production experience.
Why Environment Configuration Matters
In development, you might store API keys, database credentials, and other sensitive information in local files. But in production, this approach is risky and inefficient. Proper environment configuration helps:
- Security – Keep sensitive data out of your source code.
- Scalability – Easily adjust settings without modifying code.
- Portability – Deploy the same code across different environments.
Using .env
Files for Configuration
One of the easiest ways to manage environment variables is by using a .env
file and the dotenv
package.
Step 1: Install dotenv
npm install dotenv
Step 2: Create a .env
File
In your project root, create a .env
file and add key-value pairs:
PORT=3000
DATABASE_URL=mongodb+srv://user:password@cluster.mongodb.net/dbname
SECRET_KEY=mysecretkey
Step 3: Load Environment Variables in Your App
Modify your server.js
or app.js
file:
require('dotenv').config();
const port = process.env.PORT || 3000;
console.log(`Server running on port ${port}`);
Setting Up Environment Variables in Production
Heroku
Heroku allows you to set environment variables using the CLI:
heroku config:set DATABASE_URL=mongodb+srv://user:password@cluster.mongodb.net/dbname
Access it in your code:
const dbUrl = process.env.DATABASE_URL;
Docker
If you are running your app in a Docker container, you can pass environment variables in the docker run
command:
docker run -e PORT=3000 -e SECRET_KEY=mysecretkey my-node-app
Or define them in a docker-compose.yml
file:
version: '3'
services:
app:
image: my-node-app
environment:
- PORT=3000
- SECRET_KEY=mysecretkey
Handling Different Environments (Development, Staging, Production)
Your app may need different configurations for various environments. A good approach is to use NODE_ENV
.
Setting NODE_ENV
Set the environment variable in your .env
file or production environment:
NODE_ENV=production
Using It in Code
if (process.env.NODE_ENV === 'production') {
console.log('Running in production mode');
} else {
console.log('Running in development mode');
}
Logging and Monitoring in Production
Logging is crucial in production to debug errors and monitor performance.
Use winston
for Logging
npm install winston
Example usage:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' })
]
});
logger.info('Application started');
Use pm2
for Process Management
PM2 helps keep your app running even after crashes.
npm install -g pm2
pm2 start server.js --name my-app
To restart the app automatically:
pm2 startup
pm2 save
Conclusion
Configuring your environment properly in production ensures security, scalability, and smooth operation. By using .env
files, managing different environments, logging, and monitoring, your Node.js app will be well-prepared for real-world use. Now, go forth and deploy with confidence!
0 Comments