Environments, Config and Secrets
Run the same code in development, preview and production by keeping configuration in environment variables, validated at startup.
Intermediate · about 3 hours · difficulty 2/5
Learn first: Node.js Runtime Essentials, Runtime Validation with Zod
A deployable app reads everything that differs between environments from configuration, not from code. This is the core idea of the Twelve-Factor App.
Environments
- Development on your laptop with a local database.
- Preview deployments for each pull request, so reviewers can click through changes.
- Production with real users and data.
Each has its own database, secrets and URLs. Never point development at the production database.
Managing config
- Keep a committed .env.example listing every variable with dummy values; keep real .env files out of Git.
- Validate env vars at startup with Zod and fail fast on missing values.
- Store production secrets in the platform's environment settings or a secret manager.
- In Next.js, only NEXT_PUBLIC_ variables reach the browser, and they are baked in at build time.
Feature flags
Simple flags (an env variable or a database table) let you ship code turned off and enable it later, or roll out to one college first.
Pitfalls
- Hard-coded localhost URLs that break in production.
- Sharing one set of API keys across all environments.
- Changing an env var and forgetting to redeploy when the value is read at build time.
You are ready to move on when your app runs in development and production with different databases and keys, documented in .env.example and validated at boot.
Key concepts
- Twelve-Factor config
- Dev, preview and production
- .env and .env.example
- Validating env at startup
- Build-time vs runtime variables
- Secret managers
- Feature flags
Mini project
Refactor your project so every environment-specific value comes from a validated config module, add a complete .env.example, and set up separate development and production databases.
Check yourself
You changed NEXT_PUBLIC_API_URL in the hosting dashboard but the site still calls the old URL. Why?
Free resources
- The Twelve-Factor App (12factor.net)
- Next.js Environment Variables (Next.js)