tezvyn:

Environment configuration and secrets management in Node.js?

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

production safety and configuration best practices.

OUTLINE

use environment variables, load from .env file (dev only), never commit secrets.

WHY HARDCODING FAILS

If your code contains database passwords, API keys, or URLs, then every copy of the source reveals secrets. Accidentally pushing to a public repository exposes credentials instantly. Even in private repos, anyone with access sees all secrets. You cannot rotate keys without code changes and redeployment. This is fundamentally unsafe.

ENVIRONMENT VARIABLES

The 12-factor app methodology recommends externalizing configuration as environment variables. At runtime, the application reads process.env.DATABASE_URL instead of a hardcoded string. Different environments set different values: development points to a local database, staging to a staging database, production to the production database. All the same code.

DOTENV FOR LOCAL DEVELOPMENT

Manually setting environment variables before starting your app is tedious. The dotenv library solves this: create a .env file in the project root with key=value pairs. At startup, require('dotenv').config() loads the file into process.env. This is development-only convenience. Never commit .env to git; add it to .gitignore.

PRODUCTION SECRET STORES

In production, never rely on .env files. Use a secret manager: AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, or Kubernetes secrets. These provide encryption at rest, audit logging, rotation capabilities, and fine-grained access control. The application retrieves secrets at startup or on-demand, without them ever touching the filesystem.

LEAKED SECRETS RESPONSE

If a secret is accidentally committed, removing it later doesn't erase git history. Someone can still find it by cloning and inspecting old commits. The only safe response is to immediately rotate the secret (new API key, new password). Then use git-filter-branch or third-party tools to scrub history, though this is complex and not foolproof.

CONFIGURATION LAYERING

Best practice: environment variables override defaults. Have a config module that reads environment variables and provides sensible fallbacks: const dbUrl = process.env.DATABASE_URL || 'postgresql://localhost/myapp';. This allows development without a .env file while enforcing production to supply a real database.

Read the original → stackhero.io

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.