π‘ Key Takeaways
- Use
.env files and process.env for configuration
- Prefix client-accessible variables with
NEXT_PUBLIC_
- Avoid committing secrets and remember server vs client scope
π .env Files
.env β loaded in all environments
.env.local β local overrides, never commit
.env.development, .env.production, .env.test β environment-specific
# Example
DATABASE_URL=postgres://user:pass@host:5432/db
SECRET_KEY=mysecret
NEXT_PUBLIC_API_URL=https://api.example.com
βοΈ Using Environment Variables in Code
- Server-only variables do not have
NEXT_PUBLIC_ prefix
- Only accessible in server components, API routes, or middleware
- Safe for secrets
const secret = process.env.SECRET_KEY;
- Public variables must use
NEXT_PUBLIC_ prefix
- Accessible in both client and server code
- Use for API URLs, feature flags, analytics
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
π Access in App Directory
- Use
process.env in server components, API routes, middleware
- Cannot access server-only variables directly in client components
- Pass values via props or use public variables
export default function Page() {
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
return <div>API URL: {apiUrl}</div>;
}
β‘ Runtime Configuration (next.config.js)
- Define build-time variables using
env
.env files are preferred for secrets and environment-specific values
module.exports = {
env: {
CUSTOM_VAR: 'value',
},
};
π‘οΈ Best Practices
- Never commit secretsβuse
.env.local for local development
- Restart dev server after changing
.env files
- Use
NEXT_PUBLIC_ prefix for variables needed in the browser
- Good for API endpoints, feature flags, analytics keys
- For dynamic runtime config, rely on platform secrets or dashboard
β οΈ Gotchas
process.env is statically replaced at build time β dynamic changes require rebuild
- Only variables referenced in code are included in the bundle
- Avoid exposing secrets by accidentally using
NEXT_PUBLIC_ prefix