env-vars
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseVercel Environment Variables
Vercel环境变量
You are an expert in Vercel environment variable management — file conventions, the CLI, OIDC token lifecycle, and environment-specific configuration.
.envvercel env您是Vercel环境变量管理专家——熟悉文件规范、 CLI、OIDC令牌生命周期以及特定环境配置。
.envvercel env.env File Hierarchy
.env文件层级
Vercel and Next.js load environment variables in a specific order. Later files override earlier ones:
| File | Purpose | Git-tracked? |
|---|---|---|
| Default values for all environments | Yes |
| Local overrides and secrets | No (gitignored) |
| Development-specific defaults | Yes |
| Local dev overrides | No |
| Production-specific defaults | Yes |
| Local prod overrides | No |
| Test-specific defaults | Yes |
| Local test overrides | No |
Vercel和Next.js会按特定顺序加载环境变量,后续文件会覆盖先前文件的配置:
| 文件 | 用途 | 是否纳入Git追踪? |
|---|---|---|
| 所有环境的默认值 | 是 |
| 本地覆盖配置与密钥 | 否(已加入.gitignore) |
| 开发环境专属默认值 | 是 |
| 本地开发环境覆盖配置 | 否 |
| 生产环境专属默认值 | 是 |
| 本地生产环境覆盖配置 | 否 |
| 测试环境专属默认值 | 是 |
| 本地测试环境覆盖配置 | 否 |
Load Order (Next.js)
Next.js加载顺序
- (lowest priority)
.env - (development, production, or test)
.env.[environment] - (skipped in test environment)
.env.local - (highest priority, skipped in test)
.env.[environment].local
- (优先级最低)
.env - (development、production或test)
.env.[environment] - (测试环境下会跳过)
.env.local - (优先级最高,测试环境下会跳过)
.env.[environment].local
Critical Rules
关键规则
- Never commit secrets to ,
.env, or.env.development— use.env.productionvariants or Vercel environment variables.local - is always gitignored by Next.js — this is where
.env.localwrites secretsvercel env pull - Variables prefixed with are exposed to the browser bundle — never put secrets in
NEXT_PUBLIC_varsNEXT_PUBLIC_ - All other variables are server-only (API routes, Server Components, middleware)
- 绝不要提交密钥到、
.env或.env.development中——请使用.env.production变体或Vercel环境变量功能.local - Next.js默认会将加入.gitignore——
.env.local命令会将密钥写入此文件vercel env pull - 以为前缀的变量会暴露给浏览器打包文件——绝不要将密钥放入
NEXT_PUBLIC_前缀的变量中NEXT_PUBLIC_ - 所有其他变量仅在服务器端可用(API路由、Server Components、中间件)
vercel env CLI
vercel env CLI
Pull Environment Variables
拉取环境变量
bash
undefinedbash
undefinedPull 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
undefinedvercel env pull .env.production.local --environment=production
undefinedAdd Environment Variables
添加环境变量
bash
undefinedbash
undefinedInteractive — 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
undefinedvercel env add MY_SECRET --sensitive
undefinedList Environment Variables
列出环境变量
bash
undefinedbash
undefinedList all environment variables
列出所有环境变量
vercel env ls
vercel env ls
Filter by environment
按环境筛选
vercel env ls production
undefinedvercel env ls production
undefinedRemove Environment Variables
删除环境变量
bash
undefinedbash
undefinedRemove from specific environment
从特定环境删除变量
vercel env rm MY_SECRET production
vercel env rm MY_SECRET production
Remove from all environments
从所有环境删除变量
vercel env rm MY_SECRET
undefinedvercel env rm MY_SECRET
undefinedBootstrap Flow (Fresh Clone / New Machine)
初始化流程(全新克隆/新机器)
Use this sequence when setting up a project from scratch:
bash
undefined从零开始搭建项目时,请遵循以下步骤:
bash
undefined1) 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
undefinedwhile IFS='=' read -r key _; do
[[ -z "$key" || "$key" == #* ]] && continue
grep -q "^${key}=" .env.local || echo "Missing in .env.local: $key"
done < .env.example
undefinedTemporary Path: Run With Vercel Envs Without Writing a File
临时方案:无需写入文件即可使用Vercel环境变量运行项目
If you need Vercel environment variables immediately but do not want to write yet:
.env.localbash
vercel env run -- npm run devThis is useful for quick validation during bootstrap, but still pull for a normal local workflow.
.env.local如果您需要立即使用Vercel环境变量,但暂时不想写入文件:
.env.localbash
vercel env run -- npm run dev这在初始化期间的快速验证中非常有用,但在常规本地工作流中仍需拉取文件。
.env.localRe-pull After Secret or Provisioning Changes
密钥或配置变更后重新拉取
After creating/updating secrets (, dashboard changes) or provisioning integrations that add env vars (for example Neon/Upstash), re-run:
vercel env addbash
vercel env pull .env.local --yes在创建/更新密钥(、控制台变更)或配置集成(例如Neon/Upstash)添加环境变量后,请重新运行:
vercel env addbash
vercel env pull .env.local --yesOIDC 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
工作原理
- On Vercel deployments: is automatically injected as a short-lived JWT and auto-refreshed — zero configuration needed
VERCEL_OIDC_TOKEN - Local development: provisions a
vercel env pull .env.localvalid for ~12 hoursVERCEL_OIDC_TOKEN - Token expiry: When the local OIDC token expires, re-run to get a fresh one. Consider re-pulling at the start of each dev session to avoid mid-session auth failures
vercel env pull .env.local --yes
- Vercel部署环境:会自动注入为短期JWT并自动刷新——无需任何配置
VERCEL_OIDC_TOKEN - 本地开发环境:会生成有效期约12小时的
vercel env pull .env.localVERCEL_OIDC_TOKEN - 令牌过期:当本地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故障排查
| Symptom | Cause | Fix |
|---|---|---|
| Haven't pulled env vars | |
| Auth errors after ~12h locally | Token expired | |
| Works on Vercel, fails locally | Token not in | |
| Both set, key takes priority | Remove |
| 症状 | 原因 | 解决方法 |
|---|---|---|
本地环境缺少 | 未拉取环境变量 | |
| 本地开发约12小时后出现认证错误 | 令牌已过期 | |
| 在Vercel上正常运行,但本地环境失败 | | |
| 两者均设置时,密钥优先级更高 | 删除 |
Environment-Specific Configuration
特定环境配置
Vercel Dashboard vs .env Files
Vercel控制台 vs .env文件
| Use Case | Where to Set |
|---|---|
| Secrets (API keys, tokens) | Vercel Dashboard ( |
| Public config (site URL, feature flags) | |
| Local-only overrides | |
| CI/CD secrets | Vercel Dashboard ( |
| 使用场景 | 配置位置 |
|---|---|
| 密钥(API密钥、令牌) | Vercel控制台( |
| 公开配置(站点URL、功能开关) | |
| 本地专属覆盖配置 | |
| CI/CD密钥 | Vercel控制台( |
Environment Scoping on Vercel
Vercel上的环境范围设置
Variables set in the Vercel Dashboard at can be scoped to:
https://vercel.com/{team}/{project}/settings/environment-variables- Production — only production deployments
vercel.app - Preview — branch/PR deployments
- Development — and
vercel devvercel 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 devvercel env pull
一个变量可分配给其中一个、两个或全部三个环境。
Git Branch Overrides
Git分支专属覆盖配置
Preview environment variables can be scoped to specific Git branches:
bash
undefined预览环境变量可限定到特定Git分支:
bash
undefinedAdd a variable only for the "staging" branch
仅为"staging"分支添加变量
echo "staging-value" | vercel env add DATABASE_URL preview --git-branch=staging
undefinedecho "staging-value" | vercel env add DATABASE_URL preview --git-branch=staging
undefinedGotchas
注意事项
vercel env pull
Overwrites Custom Variables
vercel env pullvercel env pull
会覆盖自定义变量
vercel env pullvercel env pull .env.localbash
undefinedvercel env pull .env.localbash
undefinedSave 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脚本不会自动加载.env.local
.env.localOnly Next.js auto-loads . Standalone scripts (, , custom Node scripts) need explicit loading:
.env.localdrizzle-kittsxbash
undefined只有Next.js会自动加载。独立脚本(、、自定义Node脚本)需要显式加载:
.env.localdrizzle-kittsxbash
undefinedUse 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
undefinedsource <(grep -v '^#' .env.local | sed 's/^/export /') && node scripts/migrate.js
undefinedBest Practices
最佳实践
- Use as part of your setup workflow — document it in your README
vercel env pull - Never hardcode secrets — always use environment variables
- Scope narrowly — don't give preview deployments production database access
- Rotate OIDC tokens regularly in local dev — re-pull when you see auth errors
- Use — commit a template with empty values so teammates know which vars are needed
.env.example - Prefix client-side vars with — and never put secrets in them
NEXT_PUBLIC_ - Keep custom vars in — protects them from
.env.development.localoverwritesvercel env pull
- 将纳入您的初始化工作流——在README中记录此步骤
vercel env pull - 绝不要硬编码密钥——始终使用环境变量
- 最小化范围——不要给预览部署赋予生产数据库的访问权限
- 定期在本地开发环境轮换OIDC令牌——出现认证错误时重新拉取
- 使用——提交一个包含空值的模板,让团队成员了解需要哪些变量
.env.example - 客户端变量添加前缀——绝不要将密钥放入其中
NEXT_PUBLIC_ - 将自定义变量保存在中——避免被
.env.development.local覆盖vercel env pull