Vercel 03 ▲ Environment Variables & Secrets — Configuring per-environment values, sensitive variables, and shared team scopes
Environment variables represent the configuration layer that separates application logic from infrastructure-specific data. In a modern frontend workflow, a single codebase must often interface with multiple external services—databases, payment gateways, and authentication providers—each requiring unique credentials depending on the deployment stage. Vercel provides a centralized, encrypted management system that allows developers to define these variables and inject them into the application’s runtime without ever exposing sensitive secrets in source control.
The complexity of environment management on Vercel is handled through a system of scopes and contexts. By categorizing variables into Production, Preview, and Development, Vercel ensures that developers don’t accidentally wipe a production database during a local test or leak a secret through a public-facing JavaScript bundle. This system is designed to provide a “source of truth” that syncs seamlessly between the cloud dashboard and the local developer workstation, maintaining strict security boundaries while enabling high-velocity feature development.
This chapter covers the creation and management of environment variables through the Vercel Dashboard and CLI, the security implications of client-side versus server-side prefixes, and the utilization of built-in system variables. The sections that follow detail the technical hierarchy of variable injection, the mechanics of syncing local environments, and the best practices for managing shared team secrets in collaborative projects.
Key point: Environment variables on Vercel are encrypted at rest and can be strictly scoped to Production, Preview, or Development environments; variables changed in the dashboard only take effect after a new deployment is triggered.
Why X exists
The hardcoded secret problem. Storing API keys or database passwords directly in the source code is a critical security vulnerability. If a repository is compromised or accidentally made public, the credentials are lost. Environment variables allow these secrets to be stored in an encrypted cloud vault and injected at the process level during execution.
The environment drift problem. Manual synchronization of .env files across a team leads to situations where one developer has an outdated API key while another is using a newer version. Vercel exists to provide a centralized hub where the entire team pulls from the same set of configuration values, ensuring environment parity.
The accidental client-side exposure problem. Modern frameworks like Next.js bundle code for the browser. Without a strict naming convention, a developer might accidentally include a server-side secret (like a Stripe Secret Key) in a client-side component. Vercel integrates with framework-specific prefixes to prevent this “leakage” by default.
The staging vs. production collision. Using a live production database for testing a new feature in a pull request is dangerous. Vercel’s scoping system allows developers to assign a “Sandbox” database URL to the Preview environment and a “Live” URL to the Production environment using the exact same variable name.
The build-time vs. runtime trade-off. Some configuration values are needed during the compilation phase (like a build-time feature flag), while others are needed when the serverless function executes. Vercel manages the injection of these variables into both the build container and the serverless runtime environment automatically.
a. Managing Variables via Dashboard and CLI
The Vercel Dashboard provides a graphical interface for managing project settings. When adding a variable, you define the Key, the Value, and the Environment(s) where it should be active. For maximum security, Vercel offers a “Sensitive Value” option, which hides the value from other team members in the UI once it has been saved, though it remains accessible to the build and runtime processes.
# Pulling cloud variables to your local machine
# This creates a .env.local file based on the 'Development' scope
vercel env pull .env.local
The Vercel CLI is the primary tool for synchronizing local development with cloud configuration. Using vercel env pull fetches the variables defined in the “Development” scope and saves them to a local file. This eliminates the need to manually share .env files over Slack or email. Conversely, vercel env add allows developers to push new variables directly to the cloud without leaving the terminal.
It is important to remember that environment variables are “baked in” at build time for static assets and initialized at boot time for serverless functions. If you update a variable in the dashboard, you must trigger a new deployment (by pushing code or using the “Redeploy” button) for the change to propagate to your live site.
b. Security: Framework Prefixes and Client-Side Exposure
Security in frontend applications is largely about controlling what data is sent to the user’s browser. Most frameworks supported by Vercel use a prefix system to identify variables that are safe to expose to the client. For example, in Next.js, only variables prefixed with NEXT_PUBLIC_ are included in the JavaScript bundle sent to the browser.
// This will be available in the browser
const publicKey = process.env.NEXT_PUBLIC_STRIPE_KEY;
// This will be UNDEFINED in the browser, but available in serverless functions
const secretKey = process.env.STRIPE_SECRET_KEY;
If you omit the prefix, the variable is only available in the Node.js runtime (Server-Side Rendering, API Routes, or Server Actions). This is a critical safety feature. Even if a variable is defined in the Vercel Dashboard, Vercel will not expose it to the client-side code unless the framework-specific prefix is present, preventing accidental leakage of sensitive tokens.
In addition to user-defined variables, Vercel provides a toggle for “Automatically expose System Environment Variables.” When enabled, your project gains access to metadata about the deployment, such as VERCEL_URL, VERCEL_ENV, and VERCEL_REGION. These are invaluable for building dynamic links or logging which data center is handling a specific request.
c. Scoping and Team Collaboration
In a team environment, environment variables can be scoped at the Project level or the Team level. Project-level variables apply only to a specific repository. Team-level variables (available on Pro and Enterprise plans) can be shared across multiple projects, which is ideal for organizational constants like a shared internal API gateway or a corporate analytics ID.
# Example: Adding a variable to only the Production environment
vercel env add DATABASE_URL production
Scoping also applies to Git branches. While the standard scopes are Development, Preview, and Production, Vercel allows for “Branch Specific” environment variables. If you have a long-lived feature branch (e.g., release-v2), you can assign specific variables that only trigger when that branch is deployed, allowing for granular control over staging environments.
For security-conscious teams, Vercel supports “Environment Variable Protection.” This ensures that certain sensitive variables can only be modified by Project Administrators or Team Owners. Furthermore, Vercel’s audit logs track every change made to environment variables, providing a clear history of who modified a secret and when, which is essential for compliance and debugging.
Complete Example Session
# ============================================
# PART 1: AUTHENTICATING THE CLI
# ============================================
vercel login # Logs into your Vercel account
# ============================================
# PART 2: LINKING THE PROJECT
# ============================================
vercel link # Associates the local folder with a cloud project
# ============================================
# PART 3: ADDING A SERVER-SIDE SECRET
# ============================================
# This variable will NOT be visible in the browser
vercel env add STRIPE_SECRET_KEY production
# Enter value when prompted: sk_live_...
# ============================================
# PART 4: ADDING A CLIENT-SIDE PUBLIC VAR
# ============================================
# The NEXT_PUBLIC prefix makes it safe for the browser
vercel env add NEXT_PUBLIC_ANALYTICS_ID production,preview,development
# Value: UA-12345678
# ============================================
# PART 5: SYNCING FOR LOCAL DEVELOPMENT
# ============================================
# Pulls the 'development' scope variables to .env.local
vercel env pull .env.local
# ============================================
# PART 6: VERIFYING THE LOCAL SETUP
# ============================================
cat .env.local # Check that variables are present (verify .gitignore first!)
# ============================================
# PART 7: USING VARIABLES IN NEXT.JS (API)
# ============================================
# File: pages/api/pay.js
# export default function handler(req, res) {
# const key = process.env.STRIPE_SECRET_KEY; // Accessing the secret
# res.status(200).json({ status: 'ok' });
# }
# ============================================
# PART 8: TRIGGERING A NEW DEPLOYMENT
# ============================================
# Changes to variables require a fresh build
git commit -m "update environment config"
git push origin main
# ============================================
# PART 9: ACCESSING SYSTEM VARIABLES
# ============================================
# Ensure "Automatically expose System Environment Variables" is ON in Dashboard
# console.log(process.env.VERCEL_URL);
# ============================================
# PART 10: LISTING CURRENT VARIABLES
# ============================================
vercel env ls # Shows all configured variables and their scopes
The steps above demonstrate the full lifecycle of an environment variable: from creation in the cloud and synchronization to local development, to implementation in code and final deployment.
Quick Reference
Environment Scopes
| Scope | Usage Context | Sync Tool |
|---|---|---|
| Development | Local coding on your machine | vercel env pull |
| Preview | Pull Requests & non-main branches | Automatic via Git Push |
| Production | The live site (Main branch) | Automatic via Git Merge |
Framework Prefixes (Client Exposure)
| Framework | Prefix | Example |
|---|---|---|
| Next.js | NEXT_PUBLIC_ | NEXT_PUBLIC_API_URL |
| Vite | VITE_ | VITE_APP_TITLE |
| Nuxt | NUXT_PUBLIC_ | NUXT_PUBLIC_BASE_URL |
| Create React App | REACT_APP_ | REACT_APP_VERSION |
Common Reserved System Variables
| Variable | Description | Example |
|---|---|---|
VERCEL_ENV | Context of the build | production |
VERCEL_URL | Deployment unique URL | my-app-7x9z2.vercel.app |
VERCEL_REGION | Deployment region | sfo1 |
VERCEL_GIT_COMMIT_SHA | The Git SHA hash | c0ffee... |
Best Practices
✅ Do This:
// Use prefixes for public values only
const id = process.env.NEXT_PUBLIC_GA_ID; // ✅
// Always add .env.local to .gitignore
# .gitignore
.env.local // ✅
// Pull vars via CLI to ensure team parity
vercel env pull .env.local // ✅
// Scope production DB keys ONLY to Production
// (Managed in Vercel Dashboard) // ✅
❌ Don’t Do This:
// Prefix a sensitive secret with PUBLIC
const key = process.env.NEXT_PUBLIC_STRIPE_SECRET; // ❌
// Commit .env files to GitHub/GitLab
// (Always use the dashboard or CLI) // ❌
// Share secrets via plain text chat
// (Use Vercel CLI or a password manager) // ❌
// Expect variable changes to work without a redeploy
// (Variables are injected at build/boot time) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
Variable is undefined | Prefixes missing or wrong scope | Ensure NEXT_PUBLIC_ prefix for browser code |
| Local dev doesn’t match cloud | Forgot to run env pull | Run vercel env pull .env.local |
| Secret leaked in JS bundle | Secret variable had a public prefix | Rename variable and remove the public prefix |
| PR build fails | Variable not scoped to “Preview” | Check environment checkboxes in Vercel UI |
| Values are “stale” | Deployment not triggered after change | Deploy a new version of the site |
| CLI authentication error | Token expired or wrong team | Run vercel login or vercel switch |
Real-World Examples
1. Dynamic API Base URL
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000';
2. Stripe Production vs Test Key
const stripeKey = process.env.STRIPE_SECRET_KEY; // Scoped per env
3. Database Connection Pooling
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
4. Disabling Analytics in Preview
if (process.env.VERCEL_ENV === 'production') { initAnalytics(); }
5. Absolute URL Generation
const url = `https://${process.env.VERCEL_URL}/api/og`;
6. Feature Flagging via Var
const isBeta = process.env.NEXT_PUBLIC_ENABLE_BETA === 'true';
7. Setting Node Version
{ "engines": { "node": "20.x" } }
8. Third-party Webhook Secret
const signature = req.headers['stripe-signature'];
9. Sentry Error DSN
Sentry.init({ dsn: process.env.NEXT_PUBLIC_SENTRY_DSN });
10. Manual CLI Sync for Sub-projects
vercel env pull .env.development.local --environment development
Visual
The Variable Injection Pipeline
┌─────────────────────────────────────────────────────────┐
│ VERCEL CLOUD (Dashboard / Secrets Vault) │
│ │
│ [ Encrypted Key ] ──► [ Decrypt on Build ] ──► [ Artifact ]│
│ │
│ ▲ ▲ ▲ │
│ │ │ │ │
│ DEVELOPMENT PREVIEW PRODUCTION │
│ (Local machine) (Branch Push) (Main Push) │
└─────────────────────────────────────────────────────────┘
Client-Side vs Server-Side Scoping
┌─────────────────────────────────────────────────────────┐
│ APPLICATION CODE │
│ │
│ NEXT_PUBLIC_API_URL ───────► [ BROWSER BUNDLE ] │
│ (Accessible to User) [ (Publicly Visible) ] │
│ │
│ STRIPE_SECRET_KEY ───────► [ SERVERLESS RUNTIME ] │
│ (Hidden from User) [ (Internal Only) ] │
└─────────────────────────────────────────────────────────┘
CLI Local Synchronization
┌─────────────────────────────────────────────────────────┐
│ DEVELOPER WORKSTATION │
│ │
│ Command: vercel env pull │
│ │
│ [ VERCEL API ] ──► [ Local .env.local ] ──► [ App Process ]│
│ │
│ (Ensures team members use identical mock/test keys) │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Encryption | AES-256 at rest |
| Default Production Scope | Push to main branch |
| Local Sync Command | vercel env pull |
| Browser Exposure | Prefix required (e.g. NEXT_PUBLIC_) |
| Propagation | Requires a new deployment |
| System Variables | Toggle in Project Settings |
| Maximum Size | 64KB per variable |
| Scopes | Production, Preview, Development |
Key takeaways:
- Always separate secrets from code. Use the Vercel Dashboard or CLI to manage API keys, database credentials, and private tokens.
- Understand framework prefixes. Only use prefixes like
NEXT_PUBLIC_for data that is safe for the public to see in their browser’s developer tools. - Sync local environments frequently. Run
vercel env pullwhenever you start work or when a teammate updates a shared configuration. - Scopes protect your infrastructure. Ensure production-only variables are restricted to the “Production” scope to avoid accidental data corruption during testing.
- Deployments bake in variables. If you change a variable in the cloud, remember that the live site won’t update until you trigger a fresh deployment.
Remember: Environment variables are the boundary between your logic and your data. By using Vercel’s scoped and encrypted management system, you ensure that your secrets remain hidden, your development environment remains consistent, and your production site remains secure from configuration errors.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!