env-vars

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Vercel Environment Variables

Vercel环境变量

You are an expert in Vercel environment variable management —
.env
file conventions, the
vercel env
CLI, OIDC token lifecycle, and environment-specific configuration.
您是Vercel环境变量管理专家——熟悉
.env
文件规范、
vercel env
CLI、OIDC令牌生命周期以及特定环境配置。

.env File Hierarchy

.env文件层级

Vercel and Next.js load environment variables in a specific order. Later files override earlier ones:
FilePurposeGit-tracked?
.env
Default values for all environmentsYes
.env.local
Local overrides and secretsNo (gitignored)
.env.development
Development-specific defaultsYes
.env.development.local
Local dev overridesNo
.env.production
Production-specific defaultsYes
.env.production.local
Local prod overridesNo
.env.test
Test-specific defaultsYes
.env.test.local
Local test overridesNo
Vercel和Next.js会按特定顺序加载环境变量,后续文件会覆盖先前文件的配置:
文件用途是否纳入Git追踪?
.env
所有环境的默认值
.env.local
本地覆盖配置与密钥(已加入.gitignore)
.env.development
开发环境专属默认值
.env.development.local
本地开发环境覆盖配置
.env.production
生产环境专属默认值
.env.production.local
本地生产环境覆盖配置
.env.test
测试环境专属默认值
.env.test.local
本地测试环境覆盖配置

Load Order (Next.js)

Next.js加载顺序

  1. .env
    (lowest priority)
  2. .env.[environment]
    (development, production, or test)
  3. .env.local
    (skipped in test environment)
  4. .env.[environment].local
    (highest priority, skipped in test)
  1. .env
    (优先级最低)
  2. .env.[environment]
    (development、production或test)
  3. .env.local
    (测试环境下会跳过)
  4. .env.[environment].local
    (优先级最高,测试环境下会跳过)

Critical Rules

关键规则

  • Never commit secrets to
    .env
    ,
    .env.development
    , or
    .env.production
    — use
    .local
    variants or Vercel environment variables
  • .env.local
    is always gitignored by Next.js — this is where
    vercel env pull
    writes secrets
  • Variables prefixed with
    NEXT_PUBLIC_
    are exposed to the browser bundle — never put secrets in
    NEXT_PUBLIC_
    vars
  • All other variables are server-only (API routes, Server Components, middleware)
  • 绝不要提交密钥
    .env
    .env.development
    .env.production
    中——请使用
    .local
    变体或Vercel环境变量功能
  • Next.js默认会将
    .env.local
    加入.gitignore——
    vercel env pull
    命令会将密钥写入此文件
  • NEXT_PUBLIC_
    为前缀的变量会暴露给浏览器打包文件——绝不要将密钥放入
    NEXT_PUBLIC_
    前缀的变量中
  • 所有其他变量仅在服务器端可用(API路由、Server Components、中间件)

vercel env CLI

vercel env CLI

Pull Environment Variables

拉取环境变量

bash
undefined
bash
undefined

Pull all env vars for the current environment into .env.local

将当前环境的所有环境变量拉取到.env.local

vercel env pull .env.local
vercel env pull .env.local

Pull for a specific environment

拉取特定环境的变量

vercel env pull .env.local --environment=production vercel env pull .env.local --environment=preview vercel env pull .env.local --environment=development
vercel env pull .env.local --environment=production vercel env pull .env.local --environment=preview vercel env pull .env.local --environment=development

Overwrite existing file without prompting

无需确认直接覆盖现有文件

vercel env pull .env.local --yes
vercel env pull .env.local --yes

Pull to a custom file

拉取到自定义文件

vercel env pull .env.production.local --environment=production
undefined
vercel env pull .env.production.local --environment=production
undefined

Add Environment Variables

添加环境变量

bash
undefined
bash
undefined

Interactive — prompts for value and environments

交互式模式——提示输入值和指定环境

vercel env add MY_SECRET
vercel env add MY_SECRET

Non-interactive

非交互式模式

echo "secret-value" | vercel env add MY_SECRET production
echo "secret-value" | vercel env add MY_SECRET production

Add to multiple environments

添加到多个环境

echo "secret-value" | vercel env add MY_SECRET production preview development
echo "secret-value" | vercel env add MY_SECRET production preview development

Add a sensitive variable (encrypted, not shown in logs)

添加敏感变量(已加密,不会在日志中显示)

vercel env add MY_SECRET --sensitive
undefined
vercel env add MY_SECRET --sensitive
undefined

List Environment Variables

列出环境变量

bash
undefined
bash
undefined

List all environment variables

列出所有环境变量

vercel env ls
vercel env ls

Filter by environment

按环境筛选

vercel env ls production
undefined
vercel env ls production
undefined

Remove Environment Variables

删除环境变量

bash
undefined
bash
undefined

Remove from specific environment

从特定环境删除变量

vercel env rm MY_SECRET production
vercel env rm MY_SECRET production

Remove from all environments

从所有环境删除变量

vercel env rm MY_SECRET
undefined
vercel env rm MY_SECRET
undefined

Bootstrap Flow (Fresh Clone / New Machine)

初始化流程(全新克隆/新机器)

Use this sequence when setting up a project from scratch:
bash
undefined
从零开始搭建项目时,请遵循以下步骤:
bash
undefined

1) Link first so pulls target the correct Vercel project

1) 先关联项目,确保拉取的目标是正确的Vercel项目

vercel link --yes --project <name-or-id> --scope <team>
vercel link --yes --project <name-or-id> --scope <team>

2) Pull env vars into .env.local

2) 将环境变量拉取到.env.local

vercel env pull .env.local --yes
vercel env pull .env.local --yes

3) Verify required keys from .env.example exist in .env.local

3) 验证.env.example中的必填密钥是否存在于.env.local中

while IFS='=' read -r key _; do [[ -z "$key" || "$key" == #* ]] && continue grep -q "^${key}=" .env.local || echo "Missing in .env.local: $key" done < .env.example
undefined
while IFS='=' read -r key _; do [[ -z "$key" || "$key" == #* ]] && continue grep -q "^${key}=" .env.local || echo "Missing in .env.local: $key" done < .env.example
undefined

Temporary Path: Run With Vercel Envs Without Writing a File

临时方案:无需写入文件即可使用Vercel环境变量运行项目

If you need Vercel environment variables immediately but do not want to write
.env.local
yet:
bash
vercel env run -- npm run dev
This is useful for quick validation during bootstrap, but still pull
.env.local
for a normal local workflow.
如果您需要立即使用Vercel环境变量,但暂时不想写入
.env.local
文件:
bash
vercel env run -- npm run dev
这在初始化期间的快速验证中非常有用,但在常规本地工作流中仍需拉取
.env.local
文件。

Re-pull After Secret or Provisioning Changes

密钥或配置变更后重新拉取

After creating/updating secrets (
vercel env add
, dashboard changes) or provisioning integrations that add env vars (for example Neon/Upstash), re-run:
bash
vercel env pull .env.local --yes
在创建/更新密钥(
vercel env add
、控制台变更)或配置集成(例如Neon/Upstash)添加环境变量后,请重新运行:
bash
vercel env pull .env.local --yes

OIDC Token Lifecycle

OIDC令牌生命周期

Vercel uses OIDC (OpenID Connect) tokens for secure, keyless authentication between your app and Vercel services (AI Gateway, storage, etc.).
Vercel使用**OIDC(OpenID Connect)**令牌,在您的应用与Vercel服务(AI网关、存储等)之间实现安全的无密钥认证。

How It Works

工作原理

  1. On Vercel deployments:
    VERCEL_OIDC_TOKEN
    is automatically injected as a short-lived JWT and auto-refreshed — zero configuration needed
  2. Local development:
    vercel env pull .env.local
    provisions a
    VERCEL_OIDC_TOKEN
    valid for ~12 hours
  3. Token expiry: When the local OIDC token expires, re-run
    vercel env pull .env.local --yes
    to get a fresh one. Consider re-pulling at the start of each dev session to avoid mid-session auth failures
  1. Vercel部署环境
    VERCEL_OIDC_TOKEN
    会自动注入为短期JWT并自动刷新——无需任何配置
  2. 本地开发环境
    vercel env pull .env.local
    会生成有效期约12小时的
    VERCEL_OIDC_TOKEN
  3. 令牌过期:当本地OIDC令牌过期时,重新运行
    vercel env pull .env.local --yes
    获取新令牌。建议在每个开发会话开始时重新拉取,避免会话中途出现认证失败

Common OIDC Patterns

常见OIDC使用模式

ts
// The @vercel/oidc package reads VERCEL_OIDC_TOKEN automatically
import { getVercelOidcToken } from '@vercel/oidc'

// AI Gateway uses OIDC by default — no manual token handling needed
import { gateway } from 'ai'
const result = await generateText({
  model: gateway('openai/gpt-5.2'),
  prompt: 'Hello',
})
ts
// @vercel/oidc包会自动读取VERCEL_OIDC_TOKEN
import { getVercelOidcToken } from '@vercel/oidc'

// AI网关默认使用OIDC——无需手动处理令牌
import { gateway } from 'ai'
const result = await generateText({
  model: gateway('openai/gpt-5.2'),
  prompt: 'Hello',
})

Troubleshooting OIDC

OIDC故障排查

SymptomCauseFix
VERCEL_OIDC_TOKEN
missing locally
Haven't pulled env vars
vercel env pull .env.local
Auth errors after ~12h locallyToken expired
vercel env pull .env.local --yes
Works on Vercel, fails locallyToken not in
.env.local
vercel env pull .env.local
AI_GATEWAY_API_KEY
vs OIDC
Both set, key takes priorityRemove
AI_GATEWAY_API_KEY
to use OIDC
症状原因解决方法
本地环境缺少
VERCEL_OIDC_TOKEN
未拉取环境变量
vercel env pull .env.local
本地开发约12小时后出现认证错误令牌已过期
vercel env pull .env.local --yes
在Vercel上正常运行,但本地环境失败
.env.local
中无令牌
vercel env pull .env.local
AI_GATEWAY_API_KEY
与OIDC共存
两者均设置时,密钥优先级更高删除
AI_GATEWAY_API_KEY
以使用OIDC

Environment-Specific Configuration

特定环境配置

Vercel Dashboard vs .env Files

Vercel控制台 vs .env文件

Use CaseWhere to Set
Secrets (API keys, tokens)Vercel Dashboard (
https://vercel.com/{team}/{project}/settings/environment-variables
) or
vercel env add
Public config (site URL, feature flags)
.env
or
.env.[environment]
files
Local-only overrides
.env.local
CI/CD secretsVercel Dashboard (
https://vercel.com/{team}/{project}/settings/environment-variables
) with environment scoping
使用场景配置位置
密钥(API密钥、令牌)Vercel控制台(
https://vercel.com/{team}/{project}/settings/environment-variables
)或
vercel env add
命令
公开配置(站点URL、功能开关)
.env
.env.[environment]
文件
本地专属覆盖配置
.env.local
CI/CD密钥Vercel控制台(
https://vercel.com/{team}/{project}/settings/environment-variables
)并设置环境范围

Environment Scoping on Vercel

Vercel上的环境范围设置

Variables set in the Vercel Dashboard at
https://vercel.com/{team}/{project}/settings/environment-variables
can be scoped to:
  • Production — only
    vercel.app
    production deployments
  • Preview — branch/PR deployments
  • Development
    vercel dev
    and
    vercel env pull
A variable can be assigned to one, two, or all three environments.
在Vercel控制台
https://vercel.com/{team}/{project}/settings/environment-variables
中设置的变量可限定范围:
  • 生产环境——仅适用于
    vercel.app
    生产部署
  • 预览环境——分支/PR部署
  • 开发环境——
    vercel dev
    vercel env pull
一个变量可分配给其中一个、两个或全部三个环境。

Git Branch Overrides

Git分支专属覆盖配置

Preview environment variables can be scoped to specific Git branches:
bash
undefined
预览环境变量可限定到特定Git分支:
bash
undefined

Add a variable only for the "staging" branch

仅为"staging"分支添加变量

echo "staging-value" | vercel env add DATABASE_URL preview --git-branch=staging
undefined
echo "staging-value" | vercel env add DATABASE_URL preview --git-branch=staging
undefined

Gotchas

注意事项

vercel env pull
Overwrites Custom Variables

vercel env pull
会覆盖自定义变量

vercel env pull .env.local
replaces the entire file — any manually added variables (custom secrets, local overrides, debug flags) are lost. Always back up or re-add custom vars after pulling:
bash
undefined
vercel env pull .env.local
替换整个文件——所有手动添加的变量(自定义密钥、本地覆盖配置、调试标志)都会丢失。请始终在拉取前备份或在拉取后重新添加自定义变量:
bash
undefined

Save custom vars before pulling

拉取前保存自定义变量

grep -v '^#' .env.local | grep -v '^VERCEL_|^POSTGRES_|^NEXT_PUBLIC_' > .env.custom.bak vercel env pull .env.local --yes cat .env.custom.bak >> .env.local # Re-append custom vars

Or maintain custom vars in a separate `.env.development.local` file (loaded after `.env.local` by Next.js).
grep -v '^#' .env.local | grep -v '^VERCEL_|^POSTGRES_|^NEXT_PUBLIC_' > .env.custom.bak vercel env pull .env.local --yes cat .env.custom.bak >> .env.local # 重新追加自定义变量

或者将自定义变量维护在单独的`.env.development.local`文件中(Next.js会在`.env.local`之后加载此文件)。

Scripts Don't Auto-Load
.env.local

脚本不会自动加载
.env.local

Only Next.js auto-loads
.env.local
. Standalone scripts (
drizzle-kit
,
tsx
, custom Node scripts) need explicit loading:
bash
undefined
只有Next.js会自动加载
.env.local
。独立脚本(
drizzle-kit
tsx
、自定义Node脚本)需要显式加载:
bash
undefined

Use dotenv-cli

使用dotenv-cli

npm install -D dotenv-cli npx dotenv -e .env.local -- npx drizzle-kit push npx dotenv -e .env.local -- npx tsx scripts/seed.ts
npm install -D dotenv-cli npx dotenv -e .env.local -- npx drizzle-kit push npx dotenv -e .env.local -- npx tsx scripts/seed.ts

Or source manually

或手动加载

source <(grep -v '^#' .env.local | sed 's/^/export /') && node scripts/migrate.js
undefined
source <(grep -v '^#' .env.local | sed 's/^/export /') && node scripts/migrate.js
undefined

Best Practices

最佳实践

  1. Use
    vercel env pull
    as part of your setup workflow
    — document it in your README
  2. Never hardcode secrets — always use environment variables
  3. Scope narrowly — don't give preview deployments production database access
  4. Rotate OIDC tokens regularly in local dev — re-pull when you see auth errors
  5. Use
    .env.example
    — commit a template with empty values so teammates know which vars are needed
  6. Prefix client-side vars with
    NEXT_PUBLIC_
    — and never put secrets in them
  7. Keep custom vars in
    .env.development.local
    — protects them from
    vercel env pull
    overwrites
  1. vercel env pull
    纳入您的初始化工作流
    ——在README中记录此步骤
  2. 绝不要硬编码密钥——始终使用环境变量
  3. 最小化范围——不要给预览部署赋予生产数据库的访问权限
  4. 定期在本地开发环境轮换OIDC令牌——出现认证错误时重新拉取
  5. 使用
    .env.example
    ——提交一个包含空值的模板,让团队成员了解需要哪些变量
  6. 客户端变量添加
    NEXT_PUBLIC_
    前缀
    ——绝不要将密钥放入其中
  7. 将自定义变量保存在
    .env.development.local
    ——避免被
    vercel env pull
    覆盖

Official Documentation

官方文档