Environment Variables
Manage secrets and configuration safely, and understand exactly when a variable is exposed to the browser.
.env Files
Next.js automatically loads variables from a .env file (and its environment-specific variants) at the project root — no extra package required.
# .env.localDATABASE_URL=postgres://user:pass@localhost:5432/mydbNEXT_PUBLIC_ANALYTICS_ID=UA-12345Server-Only vs Public Variables
By default, every environment variable is available only on the server — inside Server Components, Route Handlers, and Server Actions. To expose a variable to the browser, its name must start with NEXT_PUBLIC_.
| Variable Name | Available In | Use For |
|---|---|---|
| DATABASE_URL | Server only | Database connection strings, secrets |
| API_SECRET_KEY | Server only | Third-party API keys never meant to reach a browser |
| NEXT_PUBLIC_ANALYTICS_ID | Server and client | IDs or config that's safe for anyone to see |
Anything prefixed NEXT_PUBLIC_ gets baked directly into your client-side JavaScript bundle at build time — never use that prefix for an API key, secret, or anything that shouldn't be visible to anyone inspecting your site.
Loading Order
- process.env — variables already set in the actual OS/hosting environment.
- .env.local — local overrides, loaded in all environments except test (and gitignored by default).
- .env.development / .env.production — environment-specific defaults.
- .env — the base defaults, checked into version control (no secrets here).
Common Beginner Mistakes
create-next-app already gitignores .env.local by default — never remove that entry or commit real credentials.
It will be undefined in the browser — server-only variables are stripped out of the client bundle entirely, by design.
FAQs
Yes — environment variables are read when the server starts, so changes require a restart to take effect.
In your hosting platform's dashboard or configuration (e.g. Vercel's project settings) — .env files are for local development, not typically deployed as-is.
Summary
Environment variables stay server-only unless explicitly prefixed with NEXT_PUBLIC_, keeping secrets safely out of the browser by default. Next, you'll apply this directly to building authentication.