Environment Variables
Environment variables let you store configuration values outside your code. This is crucial for keeping sensitive information like API keys and database credentials secure.
Think of environment variables as a safe where you store important keys. Your code can access them when needed, but they're not exposed in your repository.
Creating Environment Variables
Create a .env.local file in your project root:
# .env.local
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
API_KEY=your-secret-api-key
NEXT_PUBLIC_SITE_URL=http://localhost:3000
Variables prefixed with NEXT_PUBLIC_ are exposed to the browser. All other variables are only available on the server.
Using Environment Variables
Access environment variables in your code using process.env:
// Server-side (API routes, getServerSideProps)
export async function getServerSideProps() {
const dbUrl = process.env.DATABASE_URL;
// Use database URL...
return { props: {} };
}
// Client-side (only NEXT_PUBLIC_ variables)
export default function Home() {
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL;
return <div>Welcome to {siteUrl}</div>;
}
Important: Never use non-prefixed environment variables in client-side code. They won't be available and could cause errors.
Environment Variable Files
Next.js uses different environment variable files for different purposes:
.env - Default environment variables, loaded in all environments.
.env.local - Local overrides, loaded in all environments. Gitignored.
.env.development - Development-only variables.
.env.production - Production-only variables.
The loading order is: .env → .env.local → .env.[development|production]
Best Practices
Follow these best practices for environment variables:
Never commit secrets: Add .env.local to your .gitignore file.
Use descriptive names: Name variables clearly, like DATABASE_URL instead of DB.
Provide defaults: Use fallback values when variables might not be set.
const apiKey = process.env.API_KEY || 'default-key';
Document required variables: Keep a list of required environment variables in your README.
Environment variables are essential for secure, configurable applications.