12-Factor App in Node.js
The 12-factor methodology defines principles for building portable, scalable cloud-native applications. Key principles for Node.js: configuration via environment variables, stateless processes, explicit dependency declarations.
12-factor = the 'house rules' for well-behaved cloud tenants. Config in env vars (not hidden files), logs to stdout (yell out the window, let the building manager collect them), stateless processes (no hoarding stuff in your apartment between visitors), and fast move-in/move-out (disposability).
Key 12-factor principles for Node.js: (I) Codebase—one repo, multiple deploys. (III) Config—environment variables only, never hardcoded or config files in repo (use dotenv for local dev, never in production). (IV) Backing services—treat DB, queue, cache as attached resources via URLs. (VI) Processes—stateless; store session state externally. (VII) Port binding—self-contained HTTP server, not app server. (IX) Disposability—fast startup, graceful shutdown. (XI) Logs—treat logs as event streams (stdout/stderr only; let infrastructure aggregate).
Node.js aligns well with most 12-factor principles but tension exists with factor IX (disposability): Node.js startup can be slow with large dependency trees and connection pool warmup. Techniques: lazy initialization of connections, pre-warmed Lambda containers (AWS), or explicit health check readiness gates. Factor XI (logs as streams) conflicts with popular logging libraries that write to files—use structured JSON logging to stdout (pino, winston with stdout transport) and let infrastructure (Fluentd, Datadog agent) aggregate. Config via env vars has a scale problem with many services; Vault or AWS Parameter Store with startup-time injection solves this without violating the factor.
12-factor principles most relevant to Node.js: configuration exclusively via environment variables, stateless processes (no in-memory session state), logs as stdout streams (not files), explicit dependency declarations (package.json with lockfile), and graceful fast startup/shutdown. Node.js microservices naturally fit this model; friction points are startup time (warmup) and secret management at scale.
Storing secrets in .env files committed to version control violates factor III and is a common breach vector. The .env file is for local development only; production config must come from the environment via an orchestration layer (Kubernetes Secrets, AWS SSM, Vault). Libraries like dotenv should be excluded from production builds or guarded with NODE_ENV checks.