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:

EnvironmentWhen UsedExample URL
ProductionDeployed from main branchapp.vercel.app
PreviewDeployed from any other branch or PRapp-git-feature.vercel.app
DevelopmentLocal dev server (vercel dev)localhost:3000

Setting Variables in the Dashboard

  1. Navigate to your project on vercel.com
  2. Go to Settings then Environment Variables
  3. Add a key-value pair and select the target environments
  4. 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

CommandDescription
vercel env add <name>Add a new variable (prompts for value)
vercel env rm <name>Remove a variable
vercel env lsList 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):

  1. .env.$(NODE_ENV).local — e.g., .env.development.local
  2. .env.local — Local overrides (gitignored)
  3. .env.$(NODE_ENV) — e.g., .env.development
  4. .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.local or any file containing secrets. Add it to .gitignore and use vercel env pull to sync variables for local development.