Next.js Environment Variables: NEXT_PUBLIC_, Server-Only Secrets, and Startup Validation
Leaked secrets are one of the most common causes of production security incidents. Next.js has specific rules about which environment variables are exposed to the browser -- break them and your API...

Source: DEV Community
Leaked secrets are one of the most common causes of production security incidents. Next.js has specific rules about which environment variables are exposed to the browser -- break them and your API keys go public. The Two Worlds Next.js runs code in two environments: Server: API routes, Server Components, middleware -- has full access to all env vars Browser: Client Components -- only has access to NEXT_PUBLIC_* variables This distinction is enforced at build time. Non-public vars are stripped from browser bundles. NEXT_PUBLIC_ Variables Prefix with NEXT_PUBLIC_ to expose to the browser: # .env.local NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_live_xxx # Safe to expose NEXT_PUBLIC_SITE_URL=https://myapp.com # Safe to expose NEXT_PUBLIC_POSTHOG_KEY=phc_xxx # Safe to expose STRIPE_SECRET_KEY=sk_live_xxx # NEVER expose -- server only DATABASE_URL=postgresql://... # NEVER expose -- server only ANTHROPIC_API_KEY=sk-ant-xxx # NEVER expose -- server only NEXTAUTH_SECRET=xxx # NEVER expose -- server