Configuration (Node.js)
Configuration in Node.js means managing settings that vary by environment — ports, database URLs, secrets, feature flags. The common approach reads from environment variables, often centralized into a single config module.
Node.js
Good configuration separates settings from code so one codebase runs everywhere. The base layer is environment variables (process.env), typically loaded from a .env file in development via dotenv and injected by the platform in production. This keeps secrets out of source control and lets each environment differ.
A widely used pattern is a single config.js module that reads all process.env values once, applies defaults and type coercion, validates that required variables exist (failing fast at startup if a secret is missing), and exports a typed config object. The rest of the app imports config rather than touching process.env scattered everywhere.
For more complex needs, libraries like config or convict layer per-environment JSON files and schema validation on top. Whatever the approach, the principles are constant: defaults for optional values, no secrets in the repo, and validation so a misconfigured deploy crashes immediately instead of failing mysteriously later.
Syntax
module.exports = { port: process.env.PORT || 3000 };Examples
JavaScript
// config.js — centralize and validate
require("dotenv").config();
if (!process.env.JWT_SECRET) throw new Error("JWT_SECRET required");
module.exports = {
port: Number(process.env.PORT) || 3000,
jwtSecret: process.env.JWT_SECRET,
isProd: process.env.NODE_ENV === "production",
};