Node.js API Best Practices

Chapter 1 · Practice 3 of 4

Load configuration from the environment and validate it at startup

From Project structure and configuration

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.

  1. Read process.env once in a config module.
  2. Validate it with a schema.
  3. Export a typed object and import that everywhere else.

Node.js can now load a .env file itself, no package needed:

  • --env-file=.env loads the file.
  • --env-file-if-exists=.env loads 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

TypeScript
// 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