Introduction

The ArkEnv integration for Next.js lets you validate environment variables at build-time and runtime.

Important

This integration requires ArkType to be installed.

Features

  • Compile-Time Validation: Enforces that all client-side variables start with the NEXT_PUBLIC_ prefix and checks that all client/shared variables are explicitly mapped in the runtimeEnv object for Next.js compiler inlining.
  • Runtime Protection: Wraps the validated environment object in a Proxy. Accessing server-only variables from Client Components (during either server-side pre-rendering/SSR or browser runtime execution) throws a descriptive runtime error using package conditional exports (react-server vs. default).
  • Minimal Boilerplate: Server-only variables are dynamically fallback-read from process.env at runtime, meaning they do not need to be manually mapped inside the runtimeEnv parameter.

Quickstart

1. Installation

npm install @arkenv/nextjs arktype
pnpm add @arkenv/nextjs arktype
yarn add @arkenv/nextjs arktype
bun add @arkenv/nextjs arktype

2. Configure Environment

Create an env.ts file (typically in src/env.ts or at the root of your project) to define and validate your schemas:

src/env.ts
import  from "@arkenv/nextjs";

export const  = ({
	: {
		: "string",
	},
	: {
		: "string",
	},
	: {
		: "string",
	},
	: {
		: ..,
		: ..,
	},
});

3. Use in your code

Import env throughout your Next.js application:

src/app/page.tsx
import {  } from "./env";

// Access is fully typesafe and autocompleted
const apiUrl = .;
const apiUrl: string

If you accidentally attempt to access a server-side secret in a Client Component, it will throw a descriptive runtime exception during both server-side pre-rendering (SSR) and browser runtime execution:

src/app/client-component.tsx
import {  } from "./env";

// Throws a runtime error if evaluated in a client component (during SSR or in the browser)
const dbUrl = .;
const dbUrl: string

Using Standard Schema validators (Zod, Valibot)

This integration uses ArkType for validation under the hood, which natively supports Standard Schema. You can freely mix ArkType DSL strings with Zod or Valibot validators in the same schema - no extra configuration needed.

Here is an example using Zod:

src/env.ts
import  from "@arkenv/nextjs";
import {  } from "zod";

export const  = ({
	: {
		: .().(),
	},
	: {
		: .().(),
	},
	: {
		: .(["development", "production", "test"]),
	},
	: {
		: ..,
		: ..,
	},
});