Environment Variables
Vercel lets you define environment variables scoped to specific environments. Variables
can be set through the dashboard, the CLI, or committed .env files for local development.
Environment Scopes
Every variable is assigned to one or more environments:
| Environment | When Used | Example URL |
|---|---|---|
| Production | Deployed from main branch | app.vercel.app |
| Preview | Deployed from any other branch or PR | app-git-feature.vercel.app |
| Development | Local dev server (vercel dev) | localhost:3000 |
Setting Variables in the Dashboard
- Navigate to your project on vercel.com
- Go to Settings then Environment Variables
- Add a key-value pair and select the target environments
- Click Save
Variables added in the dashboard are encrypted at rest and injected at build time.
Using the Vercel CLI
# Add a variable to all environments
vercel env add MY_API_KEY
# Add to a specific environment
vercel env add MY_API_KEY production
# List all environment variables
vercel env ls
# Pull all variables to a local .env file
vercel env pull .env.local
CLI Quick Reference
| Command | Description |
|---|---|
vercel env add <name> | Add a new variable (prompts for value) |
vercel env rm <name> | Remove a variable |
vercel env ls | List all variables |
vercel env pull <file> | Download variables to a local file |
Accessing Variables in Next.js
Next.js exposes environment variables based on their prefix:
# Server-only (available in Server Components, Route Handlers, Server Actions)
DATABASE_URL=postgres://...
# Browser + Server (prefixed with NEXT_PUBLIC_)
NEXT_PUBLIC_API_URL=https://api.example.com
// Server Component — can read any env var
const dbUrl = process.env.DATABASE_URL;
// Client Component — can only read NEXT_PUBLIC_ vars
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
Local .env Files
Next.js loads .env files in this order (highest priority first):
.env.$(NODE_ENV).local— e.g.,.env.development.local.env.local— Local overrides (gitignored).env.$(NODE_ENV)— e.g.,.env.development.env— Default values
# .env.local (gitignored — safe for secrets)
DATABASE_URL=postgres://localhost:5432/mydb
NEXT_PUBLIC_API_URL=http://localhost:3012/api
Never commit
.env.localor any file containing secrets. Add it to.gitignoreand usevercel env pullto sync variables for local development.