← Back to Blog
Deployment

Vercel Environment Variables: The Right Way to Structure a Production Secret

NEXT_PUBLIC_ prefixes, service-role keys leaking into client bundles, and missing variable declarations at build time. These are the three most common environment variable failures in AI-generated Next.js apps — and every one of them is preventable.

Environment variables are the single most common source of production deployment failures in AI-generated Next.js applications. The failures fall into three distinct categories, each with a different root cause and a different resolution.

The first category is prefix confusion. Next.js distinguishes between server-side variables and client-side variables using the NEXT_PUBLIC_ prefix. Variables without this prefix are available only in server-side code — API routes, server components, middleware. Variables with this prefix are embedded into the client-side JavaScript bundle and accessible in the browser. AI tools frequently generate code that uses NEXT_PUBLIC_ on variables that should remain server-side — database credentials, service role keys, API secrets — exposing them to every visitor who inspects the page source.

The second category is build-time unavailability. Vercel's build container does not inherit variables from your local machine. Every variable your application references must be explicitly declared in the Vercel project settings. AI tools generate code that works locally — where the developer has a .env.local file — but fails immediately in the build container where that file does not exist. The error appears as a build failure or a runtime crash on the first request.

The third category is scope misconfiguration. Vercel allows variables to be scoped to Production, Preview, and Development environments independently. AI-generated deployment guides frequently instruct developers to add variables only to Production, causing Preview branch deployments to fail. Alternatively, they instruct adding variables to all environments, which can cause development-environment credentials to appear in production builds.

The correct structure: server-side secrets (database service role keys, third-party API keys, JWT signing secrets) are declared without the NEXT_PUBLIC_ prefix, scoped only to the environments where they are needed. Client-side configuration (public API endpoints, feature flags, analytics IDs) uses the NEXT_PUBLIC_ prefix and is treated as public information. Every variable is documented in a .env.example file committed to the repository so the requirement is visible to any future developer.

Engineering Journal

Stop debugging. Start deploying.

Submit your repository in three minutes. Receive a written scope and fixed price within 12 hours.

Submit Your App for Review →