How do you add environment variables to a Next.js project?
Short answer
You create a file named .env.local in the root of your project and define key value pairs there, which Next.js automatically loads and makes available to your server side code through process.env, keeping sensitive values like API keys out of your actual source code.
Advertisement
AModel answer
You create a file named .env.local in the root of your project and define key value pairs there, which Next.js automatically loads and makes available to your server side code through process.env, keeping sensitive values like API keys out of your actual source code.
# .env.local
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
API_SECRET_KEY=your-secret-keyReal-world example
A team stores their database connection string in a .env.local file, keeping it out of version control while still making it available to their application code at runtime.
Likely follow-ups
- Should the .env.local file be committed to version control?
- What is the difference between .env, .env.local, and .env.production?
Related topics