Code Reference

Environment Variables

Next.js · Reference cheat sheet

Environment Variables

Next.js · Reference cheat sheet


📋 Overview

Next.js loads .env* files and exposes variables to Node (server) and, with a prefix, to the browser bundle. Never ship secrets with the public prefix.

🔧 Core concepts

FileTypical use
.envDefault for all environments
.env.localLocal secrets (gitignored)
.env.development / .env.productionEnv-specific defaults
.env*.localOverrides; highest priority locally
AccessVisibility
process.env.MY_SECRETServer only
process.env.NEXT_PUBLIC_*Inlined into client JS
NEXT_PUBLIC_* in Edge/MiddlewareAvailable if set at build/runtime per host

💡 Examples

.env.local:

DATABASE_URL=postgres://...
NEXT_PUBLIC_APP_URL=http://localhost:3000

Server usage:

const url = process.env.DATABASE_URL;
if (!url) throw new Error("DATABASE_URL is required");

Client usage:

"use client";
export function Banner() {
  return <p>{process.env.NEXT_PUBLIC_APP_URL}</p>;
}

⚠️ Pitfalls

  • Changing env vars often requires restarting next dev / rebuilding.
  • NEXT_PUBLIC_ values are baked in at build time for many hosts — treat them as public.
  • Don't put API keys in NEXT_PUBLIC_* even "temporarily".

On this page