LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 4113 min read

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.local
DATABASE_URL=postgres://user:pass@localhost:5432/mydb
NEXT_PUBLIC_ANALYTICS_ID=UA-12345

Server-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 NameAvailable InUse For
DATABASE_URLServer onlyDatabase connection strings, secrets
API_SECRET_KEYServer onlyThird-party API keys never meant to reach a browser
NEXT_PUBLIC_ANALYTICS_IDServer and clientIDs or config that's safe for anyone to see
NEXT_PUBLIC_ Is Permanent Exposure

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

Committing .env.local with real secrets to git

create-next-app already gitignores .env.local by default — never remove that entry or commit real credentials.

Expecting a variable without NEXT_PUBLIC_ to work in a Client Component

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.

Next Lesson →

Authentication in Next.js