Environment configuration helps your app know important settings like where to find a database or what port to use. It keeps these details separate from your code so you can change them easily.
Environment configuration in Node.js
require('dotenv').config(); const port = process.env.PORT || 3000; const dbUrl = process.env.DATABASE_URL;
Use a .env file to store environment variables as key=value pairs.
Call require('dotenv').config() at the start of your app to load these variables into process.env.
# .env file PORT=4000 DATABASE_URL=mongodb://localhost:27017/mydb
require('dotenv').config();
console.log(process.env.PORT);const port = process.env.PORT || 3000; console.log(`Server runs on port ${port}`);
This Node.js program loads environment variables from a .env file and prints a greeting with the port number. If the variables are missing, it uses default values.
/* Create a file named .env with: PORT=5000 GREETING=Hello */ import dotenv from 'dotenv'; dotenv.config(); const port = process.env.PORT || 3000; const greeting = process.env.GREETING || 'Hi'; console.log(`${greeting}, server is running on port ${port}`);
Never commit your .env file to public code repositories to keep secrets safe.
You can use different .env files for development, testing, and production environments.
Environment variables are always strings, so convert them if you need numbers or booleans.
Environment configuration separates settings from code for flexibility and security.
Use a .env file and the dotenv package to load variables into process.env.
Always provide defaults and keep secrets out of your code.