@vineforecast/next-public-env
v1.5.0
Published
Manage type-safe runtime environment variables in Next.js for both the server and the client.
Readme
Next.js Public Runtime Environment
next-public-env is a lightweight utility that dynamically injects environment
variables into your Next.js application at runtime instead of just at build time.
The Problem
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.
Features
- 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.
Installation
Install it via your preferred package manager:
yarn add next-public-envpnpm add next-public-envnpm install next-public-envGetting Started
1. Define Your Environment Config
Create a file to configure your public environment variables (e.g.,
public-env.ts).
Basic (Type-Safe):
// 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):
// 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
}),
}
);2. Add to Root Layout (App Router)
Place <PublicEnv /> in your root layout to make variables available
client-side:
// app/layout.tsx
import { PublicEnv } from './public-env';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<PublicEnv />
{children}
</body>
</html>
);
}2b. Add to _document (Pages Router)
If you are using the Pages Router, render <PublicEnvScript /> in your custom
_document.tsx to inject the runtime variables:
// pages/_document.tsx
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { PublicEnvScript } from '../public-env';
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head />
<body>
<PublicEnvScript />
<Main />
<NextScript />
</body>
</Html>
);
}
}3. Use Anywhere
Access your environment variables with full type safety:
// Server Component
import { getPublicEnv } from './public-env';
export default function ServerPage() {
const env = getPublicEnv();
return <div>API URL: {env.API_URL}</div>;
}
// Client Component
'use client';
import { getPublicEnv } from './public-env';
export function ClientComponent() {
const env = getPublicEnv();
return <div>API URL: {env.API_URL}</div>;
}Rendering Behavior
Default: Dynamic Rendering
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.
Advanced: Manual Rendering Control
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.
Using getPublicEnvAsync()
getPublicEnvAsync() is a helper function that automatically calls await
connection() 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<Suspense>boundary to allow the rest of the page to be prerendered.
import { Suspense } from 'react';
import { getPublicEnvAsync } from './public-env';
async function EnvComponent() {
const env = await getPublicEnvAsync();
return <div>API URL: {env.API_URL}</div>;
}
export default function Page() {
return (
<div>
<h1>My Page</h1>
<Suspense fallback={<div>Loading env...</div>}>
<EnvComponent />
</Suspense>
</div>
);
}API Reference
createPublicEnv(publicEnv, options)
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<EnvObject> | 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. |
| PublicEnvScript | React.Component | A React component that must be rendered in pages/_document.tsx to inject the environment variables for client-side access. |
