Configuration and Secrets in Node.js: .env Files Done Right

Leaked keys are one of the most common security incidents

API keys pushed to public GitHub repos get found by bots within minutes. Good configuration management prevents this and makes deployments predictable.

Use Environment Variables

Configuration that changes between environments — database URLs, API keys, feature flags — belongs in environment variables, not code.

Built-In .env Loading

Modern Node.js can load .env files without the dotenv package:

node --env-file=.env server.js
# .env (never commit this)
DATABASE_URL=postgres://localhost/orders
STRIPE_KEY=sk_test_...

Commit a .env.example with placeholder values instead.

Validate at Startup

Fail fast if configuration is missing or invalid:

import { z } from 'zod';

const Env = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']),
  PORT: z.coerce.number().default(3000),
  DATABASE_URL: z.string().url(),
  STRIPE_KEY: z.string().startsWith('sk_'),
});

export const env = Env.parse(process.env);

Production Secrets

Use a secret manager: AWS Secrets Manager, Azure Key Vault, Google Secret Manager, HashiCorp Vault, or your platform's encrypted environment settings.

Prevent Leaks

  • Add .env to .gitignore
  • Enable secret scanning on your repository
  • Never log full configuration
  • Never expose server secrets to frontend bundles (watch NEXT_PUBLIC_ style prefixes)
  • Rotate keys immediately if leaked — deleting the commit isn't enough

Treat every secret as if it will leak one day: scope it narrowly, rotate it regularly, and never commit it.

Arivanandhan Chitheshwaran