tezvyn:

Next.js Environment Variables: Server vs. Browser

AI-drafted, machine-checkedSource: nextjs.orgbeginner

Next.js environment variables separate server secrets from public browser config. Use them for API keys or database strings. The key footgun is exposing secrets by forgetting to prefix browser-accessible variables with `NEXT_PUBLIC_`.

WHY IT EXISTS To separate configuration from code. Hardcoding API keys, database connection strings, or other secrets is insecure and makes it difficult to manage different environments like development and production. Environment variables allow you to inject these values at build time or runtime without changing your application code.

THE MENTAL MODEL Think of two separate buckets for your variables. The first bucket is for the server, accessible only in backend code like API Routes or getServerSideProps. This is the default and it's secure. The second bucket is for the browser, and anything you put in it MUST be explicitly marked public by prefixing its name with NEXT_PUBLIC_.

HOW IT WORKS Next.js loads variables from .env files in your project root, with .env.local overriding others for local development (and should not be committed to git). A variable like DATABASE_URL is only available on the server. To expose a variable to the browser, you must prefix it, like NEXT_PUBLIC_ANALYTICS_ID. Next.js then embeds these public variables into the client-side JavaScript bundle, making them accessible via process.env.NEXT_PUBLIC_ANALYTICS_ID.

WHEN TO USE IT Use environment variables for any value that is sensitive or changes between deployment environments. This includes private API keys, database credentials, authentication secrets, and third-party service tokens. Also use them for non-secret, environment-specific settings like a public API endpoint URL that differs between development and production.

WHEN NOT TO USE IT Do not store sensitive information in any variable prefixed with NEXT_PUBLIC_. These variables are not secure; they are fully visible to anyone who inspects your website's client-side code. If a value is static, non-sensitive, and the same across all environments, it can simply be a constant in your code.

ONE CANONICAL EXAMPLE A common use case is connecting to a payment provider. You would store your secret key as STRIPE_SECRET_KEY in .env.local for use in server-side API routes to process payments. You would store your publishable key as NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY to be used in your client-side React components for initializing the Stripe.js library. This pattern keeps the secret key safe on the server while exposing only the necessary public key to the browser.

Read the original → nextjs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.