Environment Variable Management Across Environments
Beginner8 min
Configure and validate environment variables for development, staging, and production in React and Next.js projects.
Prerequisites
- -React or Next.js project
Steps
1
Create environment files for each environment
Set up .env files for local, development, and production environments.
$ echo 'NEXT_PUBLIC_API_URL=http://localhost:3001/api' > .env.local && echo 'NEXT_PUBLIC_API_URL=https://api.staging.example.com' > .env.staging && echo 'NEXT_PUBLIC_API_URL=https://api.example.com' > .env.production
Never commit .env.local or files containing secrets. Add them to .gitignore.
2
Create a .env.example file
Document all required environment variables without actual values.
$ printf 'NEXT_PUBLIC_API_URL=\nNEXT_PUBLIC_SITE_URL=\nDATABASE_URL=\nJWT_SECRET=\n' > .env.example
Commit .env.example to the repository so other developers know which variables are needed.
3
Add runtime validation with zod
Validate environment variables at startup to fail fast on missing configuration.
$ cat > src/lib/env.ts << 'EOF'
import { z } from 'zod';
const envSchema = z.object({
NEXT_PUBLIC_API_URL: z.string().url(),
NEXT_PUBLIC_SITE_URL: z.string().url().optional(),
});
export const env = envSchema.parse({
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,
});
EOF
4
Add env files to .gitignore
Ensure sensitive environment files are not committed to version control.
$ echo -e '.env\n.env.local\n.env.*.local\n.env.staging\n.env.production' >> .gitignore
5
Verify environment loading in development
Check that Next.js loads the correct variables at runtime.
$ node -e "require('dotenv').config({ path: '.env.local' }); console.log('API URL:', process.env.NEXT_PUBLIC_API_URL);"
Full Script
FAQ
Discussion
Loading comments...