Configuration & Environment
The same code runs on your laptop, in CI and in production — with a different port, database URL and log level in each place. That difference belongs in configuration, read from environment variables, never hard-coded and never committed. This follows the well-known Twelve-Factor App rule: "store config in the environment".
What counts as configuration?
| Configuration (varies per environment) | Code (same everywhere) |
|---|---|
| port, host | routes, validation rules |
| database URL, Redis URL | business logic |
| secrets: JWT secret, API keys | default page sizes |
| log level, feature flags | error messages |
| allowed CORS origins |
Reading environment variables
Everything in process.env is a string (or undefined). Convert and validate it once, at startup, in a single module — and fail fast with a clear message if something is missing:
function loadConfig(env) {
const errors = [];
const required = (name) => {
const value = env[name];
if (!value) errors.push(`${name} is required`);
return value;
};
const int = (name, fallback) => {
if (env[name] === undefined) return fallback;
const n = Number(env[name]);
if (!Number.isInteger(n)) errors.push(`${name} must be an integer, got "${env[name]}"`);
return n;
};
const config = {
env: env.NODE_ENV ?? 'development',
port: int('PORT', 3000),
databaseUrl: required('DATABASE_URL'),
jwtSecret: required('JWT_SECRET'),
corsOrigins: (env.CORS_ORIGINS ?? '').split(',').map((s) => s.trim()).filter(Boolean),
logLevel: env.LOG_LEVEL ?? 'info',
};
if (errors.length) throw new Error('Invalid configuration:\n - ' + errors.join('\n - '));
return Object.freeze(config);
}
console.log(loadConfig({
PORT: '8080',
DATABASE_URL: 'postgres://app@db/app',
JWT_SECRET: 'x'.repeat(32),
CORS_ORIGINS: 'https://app.example.com, https://admin.example.com',
}));
try {
loadConfig({ PORT: 'eighty' });
} catch (err) {
console.log(err.message);
}{
env: 'development',
port: 8080,
databaseUrl: 'postgres://app@db/app',
jwtSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
corsOrigins: [ 'https://app.example.com', 'https://admin.example.com' ],
logLevel: 'info'
}
Invalid configuration:
- PORT must be an integer, got "eighty"
- DATABASE_URL is required
- JWT_SECRET is required
Passing env as a parameter (instead of reading process.env inside) makes the loader trivial to test. In the app you call loadConfig(process.env) once and import the result everywhere.
Tip:
Object.freezestops code from accidentally changing config at runtime — config should be read-only after startup.
.env files
Typing ten variables before every node command is tedious. Locally, keep them in a .env file. Node 20.6+ can load it natively, no dotenv package required:
# .env — never commit this file!
PORT=3000
DATABASE_URL=postgres://dev:dev@localhost:5432/notes
JWT_SECRET=dev-only-secret-change-me-please-32ch
LOG_LEVEL=debugnode --env-file=.env src/server.jsConfig loaded for development (log level debug)
Listening on http://localhost:3000
| File | Committed? | Purpose |
|---|---|---|
.env |
no (add to .gitignore) |
your local values and secrets |
.env.example |
yes | documents every variable with dummy values |
--env-file-if-exists=.env |
— | Node 22.9+: don't fail when the file is missing (e.g. in production) |
In production, variables come from the platform — Docker -e/env_file, Kubernetes Secrets, your cloud provider's settings page — not from a .env file baked into the image.
NODE_ENV and Express
Express reads NODE_ENV into app.get('env'). With production it caches view templates and its default error handler stops sending stack traces. Many libraries also optimise themselves when it's set:
const express = require('express');
const app = express();
console.log('env setting :', app.get('env'));
process.env.NODE_ENV = 'production';
const prodApp = express();
console.log('env setting :', prodApp.get('env'));
console.log('view cache :', prodApp.get('view cache'));env setting : development
env setting : production
view cache : true
Note: Use
NODE_ENVonly for "production vs not". Don't invent values likeNODE_ENV=stagingto switch database URLs — configure the URL itself.
App settings
Express has its own settings table, read and written with app.set/app.get (and app.enable/app.disable for booleans):
| Setting | Effect |
|---|---|
trust proxy |
trust X-Forwarded-* headers from N proxies → correct req.ip, req.protocol |
x-powered-by |
false hides the X-Powered-By: Express header |
json spaces |
pretty-print res.json output (handy in development) |
query parser |
'simple' (default), 'extended' or a custom function |
etag |
ETag generation ('weak' by default) |
Test yourself
What type is process.env.PORT when set to 8080?
- number
- string
- bigint
- object
Which file should be committed to document required variables?
- .env
- .env.example
- node_modules/.env
- package-lock.json
When should an app detect missing configuration?
- When the first request uses it
- At startup, failing fast with a clear message
- Never — use defaults for everything
- Only in production