Add and use environment variables
careful intermediate #env#secrets#api key#config
When to use this: The site needs an API key, URL or setting that must not live in Git.
Be careful with this one. Never commit
.env files or paste real keys into code. Changes apply only to NEW deployments. Before you start
Steps
-
Add the variable in the dashboard
Project, Settings, Environment Variables. Enter the name and value, pick which environments (Production, Preview, Development), and save.
-
Or add it with the CLI
terminalnpm i -g vercel vercel link vercel env add MY_KEYvercel linkties this folder to the Vercel project.env addasks for the value and the environments. -
Copy variables to your PC for local development
terminalvercel env pull .env.localWrites a gitignored
.env.localfile sonpm run devworks with the same settings. -
Redeploy so the new value is used
terminalgit commit --allow-empty -m "Redeploy with new env" git pushExisting deployments keep the old values. Or use the dashboard: Deployments, the three dots, Redeploy.
How to verify it worked
- The new deployment works, and
vercel env lslists the variable for the right environments.
How to undo it
Remove a variable:
terminal
vercel env rm MY_KEYCommon errors and fixes
undefined in the browser, but it works locally It lacks the public prefix, or it was added after the last deploy. Rename with the prefix (PUBLIC_...) and redeploy. Works in Preview but not Production The variable is only enabled for one environment. Edit it and tick Production.
Leaked a key in Git or logs Revoke it at the provider, create a new one, update it in Vercel, and redeploy.
Q&A
Why does changing a variable not change the live site?
Values are baked in at build or deploy time. A new deployment is needed to pick up the change.
Can I put a secret in a variable with PUBLIC_ prefix?
No. The prefix means the value is bundled into browser code and is visible to every visitor.