Skip to content

Handling Next.js Environment Variables Safely Across Client and Server

Learn how to isolate runtime secrets and safely expose public configuration in Next.js applications without leaking sensitive keys.

Published 3min read
Handling Next.js Environment Variables Safely Across Client and Server
On this page

Configuring environment variables incorrectly in Next.js often leads to accidental secret leaks or broken builds when code shifts between server and client environments. By default, any variable prefixed correctly is exposed to the browser, making strict naming conventions and validation mandatory for production applications. Read on to learn how to compartmentalize your configuration, validate values at startup, and protect your application keys.

Understanding the Next.js Variable Boundary

Next.js treats environment variables differently based on their prefixes and where they are imported. Understanding this boundary protects private API keys, database credentials, and signing secrets from ending up in client-side JavaScript bundles.

Variables defined without a public prefix remain strictly on the server. They are accessible inside Server Components, Route Handlers, and Server Actions via process.env. However, the moment you import a server-only module into a Client Component, Next.js will throw an error or—worse, depending on configuration—strip or expose properties if handled improperly.

To expose a variable to the browser, you must prefix it with NEXT_PUBLIC_. Developers often make the mistake of adding this prefix to database connection strings or payment gateway private keys just to fix a missing import error on a shared utility file. Treat every public prefix as a deliberate decision to broadcast that value to any user who inspects your frontend source code.

Enforcing Strict Runtime Validation

Relying on raw process.env lookups throughout your codebase makes it difficult to catch missing configuration errors until a user triggers a broken code path in production. Instead, centralize your environment variable access and validate them using a schema parser when your application boots up.

Create a dedicated configuration module that runs on the server to check for required keys before the application starts accepting traffic. If a mandatory secret is missing, crash the build or server startup immediately rather than failing silently mid-request.

import { z } from 'zod';

const envSchema = z.object({
  DATABASE_URL: z.string().url(),
  STRIPE_SECRET_KEY: z.string().min(1),
  NEXT_PUBLIC_API_URL: z.string().url(),
});

const parsed = envSchema.safeParse(process.env);

if (!parsed.success) {
  console.error('Invalid environment variables:', parsed.error.format());
  process.exit(1);
}

export const env = parsed.data;

Import this validated object whenever you need an environment variable elsewhere in your server code. This practice guarantees type safety, autocompletion, and immediate feedback during deployment builds if a variable is omitted from your hosting provider dashboard.

Isolating Client and Server Configurations

When building applications that share utility functions between the frontend and backend, you must keep configuration separation clean. Never pass unvalidated process objects directly into shared helper functions that might run in the browser.

Adopt a file structure that separates client-safe configurations from server-only secrets. For instance, keep a config/server.ts file that references private keys and a config/client.ts file that only exposes public variables. This clear boundary prevents junior developers or automated refactoring tools from accidentally importing server utilities into client components.

  • Audit your codebase weekly for any raw process.env usage outside your dedicated configuration modules.
  • Verify that your CI/CD pipeline injects production secrets during the build phase only for variables required at build time.
  • Double-check that all third-party SDK initialization code runs exclusively within Server Components or Route Handlers if it requires private keys.

Production Checklist for Environment Variables

Before deploying your Next.js application to production, run through this checklist to ensure your configuration setup remains secure and resilient.

  1. Confirm that no private keys utilize the NEXT_PUBLIC_ prefix in your .env files.
  2. Ensure your runtime validation schema checks both presence and format, such as validating URLs and minimum string lengths.
  3. Add your local environment files, such as .env.local and .env.production.local, to your version control ignore file.
  4. Test your production build locally using environment variables matching your staging or production infrastructure.

FAQs

Frequently asked questions

Written by

Dipen Nagani, Senior UI/UX Designer

Senior UI/UX Designer

As a User Experience Designer at Seven Square®, I contribute to enhancing digital experiences by leveraging my skills in UI/UX, CSS, and GSAP. My focus is on creating intuitive and visually engaging user interfaces that align with user needs and business goals.

Keep exploring

Put these ideas into practice

Explore a relevant capability, a project example, or a checklist for your next step.

Got an idea?

Let’s turn it into something people love using.

Whether it’s a rough sketch on a napkin or a SaaS product that has grown messy over time, I’d love to hear about it. The first conversation is always free, and if you’re in Ahmedabad, the chai is on me.