How to Use Environment Variables
Complete guide for any platform
TL;DR
TL;DR: Store secrets in .env.local files locally, access them via process.env.VARIABLE_NAME in your code, and configure them in your hosting platform's dashboard for production. Never commit .env files to git.
What Are Environment Variables?
Environment variables are key-value pairs stored outside your code that configure how your application runs. They let you:
- Keep secrets (API keys, passwords) out of your codebase
- Use different values for development, staging, and production
- Change configuration without modifying code
Basic Setup
Create your .env file
Create a file named .env.local in your project root:
# .env.local
DATABASE_URL=postgresql://localhost:5432/mydb
STRIPE_SECRET_KEY=sk_test_xxxxx
OPENAI_API_KEY=sk-xxxxx
NEXT_PUBLIC_API_URL=https://api.example.com
The format is KEY=value with no spaces around the equals sign.
Add to .gitignore
Make sure .env files are never committed:
# .gitignore
.env
.env.local
.env.*.local
Access in your code
Use process.env to read values:
// In Node.js / Next.js server-side code
const apiKey = process.env.STRIPE_SECRET_KEY;
// Validate required variables
if (!process.env.DATABASE_URL) {
throw new Error('DATABASE_URL is required');
}
Framework-Specific Guides
Next.js
Next.js has built-in support for .env files:
# .env.local (for development)
DATABASE_URL=postgresql://localhost/mydb
# Variables prefixed with NEXT_PUBLIC_ are exposed to the browser
NEXT_PUBLIC_API_URL=https://api.example.com
# Variables WITHOUT the prefix stay server-side only
STRIPE_SECRET_KEY=sk_test_xxxxx
Important: Only use NEXT_PUBLIC_ for values that are safe to expose publicly. Never prefix secret keys with NEXT_PUBLIC_ .
Vite (React, Vue, Svelte)
Vite uses VITE_ prefix for client-exposed variables:
# .env.local
VITE_API_URL=https://api.example.com
VITE_APP_NAME=MyApp
# Access in code
const apiUrl = import.meta.env.VITE_API_URL;
Create React App
CRA uses REACT_APP_ prefix:
# .env.local
REACT_APP_API_URL=https://api.example.com
# Access in code
const apiUrl = process.env.REACT_APP_API_URL;
Node.js (Express, etc.)
Use the dotenv package:
npm install dotenv
// At the very top of your entry file (before other imports)
import 'dotenv/config';
// Or the CommonJS way
require('dotenv').config();
// Now process.env has your variables
const dbUrl = process.env.DATABASE_URL;
Environment Variable Naming
| Convention | Example | Usage |
|---|---|---|
| SCREAMING_SNAKE_CASE | DATABASE_URL | Standard for env vars |
| Service prefix | STRIPE_SECRET_KEY | Group by service |
| Framework prefix | NEXT_PUBLIC_ | Client exposure control |
Loading Order
Most frameworks load .env files in this order (later files override earlier):
.env- Base defaults.env.local- Local overrides (gitignored).env.development- Development-specific.env.development.local- Local dev overrides.env.production- Production-specific.env.production.local- Local prod overrides
Production Configuration
In production, don't deploy .env files. Configure variables in your hosting platform:
| Platform | Where to Configure |
|---|---|
| Vercel | Project Settings → Environment Variables |
| Netlify | Site Settings → Environment Variables |
| Railway | Project → Variables |
| Render | Service → Environment |
| Heroku | Settings → Config Vars |
| AWS | Parameter Store or Secrets Manager |
Type Safety with TypeScript
Create a typed config to catch missing variables early:
// lib/env.ts
function getEnvVar(key: string): string {
const value = process.env[key];
if (!value) {
throw new Error(`Missing environment variable: ${key}`);
}
return value;
}
export const env = {
DATABASE_URL: getEnvVar('DATABASE_URL'),
STRIPE_SECRET_KEY: getEnvVar('STRIPE_SECRET_KEY'),
// Optional variables
LOG_LEVEL: process.env.LOG_LEVEL || 'info',
} as const;
// Usage
import { env } from './lib/env';
const stripe = new Stripe(env.STRIPE_SECRET_KEY);
Do I need to restart my dev server after changing .env?
Yes, in most frameworks. Environment variables are loaded at startup. After changing .env.local, restart your development server with npm run dev.
Can I use quotes in .env files?
You can, but it's not always necessary. Use quotes when your value contains spaces or special characters: MESSAGE="Hello World". Without spaces, quotes are optional.
Why isn't my variable showing up in the browser?
Most frameworks only expose variables with specific prefixes to the browser for security. In Next.js, use NEXT_PUBLIC_. In Vite, use VITE_. In CRA, use REACT_APP_.
Related guides:How to Hide API Keys · Vercel Environment Variables · Netlify Environment Variables