Manage type-safe runtime environment variables in Next.js for both the server and the client.
npm install next-public-envnext-public-env is a lightweight utility that dynamically injects environment
variables into your Next.js application at runtime instead of just at build time.
Next.js's standard approach bakes environment variables into your application
during the build process through NEXT_PUBLIC_ variables. This means you need a
separate build for each environment; one for development, another for staging,
and yet another for production. This violates the "build once, deploy many"
principle and creates unnecessary complexity in your deployment pipeline.
- Type Safety & Validation: Integrates with Zod for schema validation, type
coercion, and full TypeScript support.
- Error-Resilient: Environment variables remain accessible even when pages
throw unhandled errors.
- Universal API: Use the same getPublicEnv() function in both Server and
Client Components.
- Lightweight: Adds only ~275 bytes to your client bundle.
Install it via your preferred package manager:
``bash`
yarn add next-public-env`bash`
pnpm add next-public-env`bash`
npm install next-public-env
Create a file to configure your public environment variables (e.g.,
public-env.ts).
Basic (Type-Safe):
`ts
// public-env.ts
import { createPublicEnv } from 'next-public-env';
export const { getPublicEnv, PublicEnv } = createPublicEnv({
NODE_ENV: process.env.NODE_ENV,
API_URL: process.env.API_URL,
MAINTENANCE_MODE: process.env.MAINTENANCE_MODE === 'true',
});
`
With Zod Validation (Recommended):
`ts
// public-env.ts
import { createPublicEnv } from 'next-public-env';
export const { getPublicEnv, PublicEnv } = createPublicEnv(
{
NODE_ENV: process.env.NODE_ENV,
API_URL: process.env.API_URL,
MAINTENANCE_MODE: process.env.MAINTENANCE_MODE,
PORT: process.env.PORT,
},
{
schema: (z) => ({
NODE_ENV: z.enum(['development', 'production', 'test']),
API_URL: z.string().url(),
MAINTENANCE_MODE: z.enum(['on', 'off']).default('off'),
PORT: z.coerce.number().default(3000), // Converts string to number
}),
}
);
`
Place in your root layout to make variables available
client-side:
`tsx
// app/layout.tsx
import { PublicEnv } from './public-env';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
$3
Access your environment variables with full type safety:
`tsx
// Server Component
import { getPublicEnv } from './public-env';export default function ServerPage() {
const env = getPublicEnv();
return
API URL: {env.API_URL};
}// Client Component
'use client';
import { getPublicEnv } from './public-env';
export function ClientComponent() {
const env = getPublicEnv();
return
API URL: {env.API_URL};
}
`Rendering Behavior
$3
When you use
getPublicEnv() in a Server Component, that route automatically
switches to dynamic rendering. This ensures your environment variables are
always read fresh from the server at request time, rather than being cached at
build time.$3
For specific use cases, you can override this behavior using the
dynamicRendering option. Set it to 'manual' to disable the automatic
noStore() call and take full control of your routes' rendering behavior.Cache Components Support
Next.js Cache Components (enabled via
cacheComponents: true in
next.config.js) prerender routes into a static HTML shell by default. This
means that environment variables are read at build time, which defeats the
purpose of next-public-env.To ensure your environment variables are read at runtime, you must opt-out of
the static shell by making your component dynamic. You can do this by using any
runtime API(like
headers(), cookies(), etc.) or by using the getPublicEnvAsync() function
provided by this library which automatically calls await connection() to
opt-out of the static shell.$3
getPublicEnvAsync() is a helper function that automatically calls await to opt-out of the static shell and returns your environment
variables.> Important: Components using
getPublicEnvAsync() (or any runtime API)
> should be wrapped in a boundary to allow the rest of the page to be
> prerendered.`tsx
import { Suspense } from 'react';
import { getPublicEnvAsync } from './public-env';async function EnvComponent() {
const env = await getPublicEnvAsync();
return
API URL: {env.API_URL};
}export default function Page() {
return (
My Page
Loading env... }>
API Reference
$3
This is the main function used to configure the library.
#### Parameters
| Parameter | Type | Required? | Description |
| :---------- | :------- | :-------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
publicEnv | object | Yes | An object that explicitly defines the variables and values to be made available. This acts as an allowlist, ensuring no other process.env variables are exposed. |
| options | object | No | An optional object for advanced configuration like schema validation and rendering behavior. |#### Options Object Properties
| Property | Type | Description |
| :-------------------- | :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
schema | (z) => ZodObject | An optional function that receives the Zod library (z) as an argument and returns a Zod schema object. The keys in the schema must match the keys in your publicEnv object. Used for validation, type coercion, and setting defaults. |
| validateAtBuildStep | boolean | If true, the library validates your publicEnv object against the schema during next build. Useful for failing builds early in CI/CD. Default: false. |
| dynamicRendering | 'auto' \| 'manual' | Controls the dynamic rendering behavior. 'auto' (default) automatically opts-out of static rendering by calling noStore(). 'manual' requires you to manage rendering behavior yourself. Warning: Using manual incorrectly can lead to undefined variables. Default: 'auto'. |#### Returns
The function returns an object containing the
getPublicEnv function and the
PublicEnv component.| Property | Type | Description |
| :------------ | :------------------ | :-------------------------------------------------------------------------------------------------------------------------------------- |
|
getPublicEnv| () => EnvObject | A function that returns your public environment variables. The return type is inferred from your publicEnv object and Zod schema. |
| getPublicEnvAsync| () => Promise | An async function that returns your public environment variables and opts-out of static rendering by calling await connection(). |
| PublicEnv | React.Component` | A React component that must be rendered in your root layout to inject the environment variables for client-side access. |