Environment Configuration
Store secrets and settings in environment variables loaded with dotenv.
Syntax
process.env.VARIABLE_NAMEConfiguration that changes between environments — database URLs, secrets, ports — should live in environment variables, not in code. Locally, the dotenv package loads them from a .env file into process.env.
Add .env to .gitignore so secrets never reach your repository.
Example
require('dotenv').config();
const config = {
port: process.env.PORT || 3000,
dbUrl: process.env.DATABASE_URL,
jwtSecret: process.env.JWT_SECRET,
};
app.listen(config.port);When to use it
- A developer stores the database URL, JWT secret, and port in a .env file so the same code runs in development and production with different settings.
- A team validates required environment variables at startup with a schema so the server fails fast with a clear error if a variable is missing.
- A twelve-factor app reads all configuration from process.env and never hard-codes credentials, making it safe to deploy to any cloud platform.
More examples
dotenv for local development
Loads .env at the top of the entry file so all subsequent process.env reads pick up local overrides.
// Load .env variables before anything else
require('dotenv').config();
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const DB = process.env.DATABASE_URL;
if (!DB) throw new Error('DATABASE_URL is required');
app.listen(PORT, () => console.log(`Running on ${PORT}`));.env file example
A sample .env file listing the most common variables for an Express + Postgres app — never commit this file to source control.
PORT=3000
NODE_ENV=development
DATABASE_URL=postgres://user:pass@localhost:5432/mydb
JWT_SECRET=supersecretkey
SESSION_SECRET=anothersecretConfig module with validation
Centralises environment variable access in a config module that throws at startup if any required variable is absent.
// config/index.js
const required = ['PORT', 'DATABASE_URL', 'JWT_SECRET'];
required.forEach(key => {
if (!process.env[key]) throw new Error(`Missing env var: ${key}`);
});
module.exports = {
port: Number(process.env.PORT),
dbUrl: process.env.DATABASE_URL,
jwtSecret: process.env.JWT_SECRET,
isProd: process.env.NODE_ENV === 'production',
};
Discussion