Chapter 1 · Practice 3 of 4
Load configuration from the environment and validate it at startup
Why it matters
Configuration such as database URLs, API keys and ports belongs in environment variables, not in code. A missing value should stop the process on boot with a clear message, not fail hours later on the first request that needs it.
- Read
process.envonce in a config module. - Validate it with a schema.
- Export a typed object and import that everywhere else.
Node.js can now load a .env file itself, no package needed:
--env-file=.envloads the file.--env-file-if-exists=.envloads it only if present, for local files that may be missing.
--env-file is no longer experimental since Node.js 24.10 and 22.21 (see the command-line docs).
Example
// config.ts
import { z } from 'zod';
const env = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']),
PORT: z.coerce.number().default(3000),
DATABASE_URL: z.url(),
}).parse(process.env);
export default env;
// node --env-file-if-exists=.env src/server.ts