Environment Variables in Next.js, React, and Vite Explained
What .env files are, which variables reach the browser (NEXT_PUBLIC_ and VITE_), how to set them on Vercel and Netlify, and how to keep secret keys secret.
By UndieGravity, , 1 min read
Environment variables hold settings that change between your computer and production: API URLs, keys, IDs. Keeping them out of the code means you can deploy the same code anywhere, and secrets never end up on GitHub.
The .env files
.env.example: committed to Git. Lists every variable the project needs, with empty or fake values..env.local(Next.js) or.env.local/.env(Vite): your real values. Never committed.- Your
.gitignoreshould contain.env*with an exception for.env.example.
# .env.example
NEXT_PUBLIC_SITE_URL=http://localhost:3000
DATABASE_URL=
RESEND_API_KEY=Server versus browser variables
This is the part that matters for security. By default, environment variables are available only on the server. To use one in browser code, it needs a prefix:
- Next.js:
NEXT_PUBLIC_(for exampleNEXT_PUBLIC_SITE_URL). - Vite:
VITE_(for exampleVITE_API_URL), read withimport.meta.env.VITE_API_URL.
Anything with these prefixes is copied into the JavaScript that visitors download. Anyone can read it. Never give a secret key, database URL, or private token a public prefix.
Public values are fixed at build time
Browser variables are inlined when the project is built. If you change NEXT_PUBLIC_SITE_URL on your host, nothing changes until you deploy again. Server-only variables in Next.js can be read at request time.
Setting them on your host
- Vercel: Project Settings, Environment Variables. Set separate values for Production and Preview.
- Netlify: Site configuration, Environment variables. Values can differ per deploy context.
- GitHub Pages: there is no server, so only build-time values apply, set in your GitHub Actions workflow if you build there.
Fail early when one is missing
const apiUrl = process.env.API_URL;
if (!apiUrl) {
throw new Error("API_URL is not set. Copy .env.example to .env.local and fill it in.");
}A clear error at startup beats a blank page in production. Validate required variables in one module and import them from there.
If a secret was committed
Deleting the file is not enough: it is still in the Git history. Rotate the key at the provider immediately, then remove it from the repository.