Next.js Environment Variables & Configuration Cheat Sheet
Next.js Environment Variables & Configuration Cheat Sheet
.env Files
.env
– loaded in all environments.env.local
– loaded in all envs, not committed.env.development
,.env.production
,.env.test
– loaded by environment.env.development.local
, etc. – local overrides
Usage in Code
Private (Server-Only) Variables
// Only available on the server
const secret = process.env.SECRET_KEY;
Public (Client-Accessible) Variables
- Must be prefixed with
NEXT_PUBLIC_
// Available on both client and server
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
Access in App Directory
- Use
process.env
in server components, API routes, and middleware. - Cannot use
process.env
directly in client components—pass as props or use public variables.
Example .env.local
DATABASE_URL=postgres://user:pass@host:5432/db
SECRET_KEY=mysecret
NEXT_PUBLIC_API_URL=https://api.example.com
Runtime Configuration (next.config.js)
// next.config.js
module.exports = {
env: {
CUSTOM_VAR: 'value', // available at build time
},
// ...other config
};
- Prefer
.env
files for secrets and environment-specific values.
Best Practices
- Never commit secrets—use
.env.local
for local dev. - Use
NEXT_PUBLIC_
prefix for variables needed in the browser. - Restart dev server after changing env files.
- Use environment variables for API endpoints, feature flags, analytics keys, etc.
- For dynamic runtime config (e.g., Vercel), use dashboard or platform secrets.
Gotchas
- process.env is statically replaced at build time—dynamic changes require a rebuild.
- Only variables referenced in code are included in the bundle.
- Do not expose secrets by omitting the
NEXT_PUBLIC_
prefix.
This cheatsheet gives developers a quick, safe, and modern reference for managing environment variables and configuration in Next.js.