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 theruntimeEnvobject 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-servervs.default). - Minimal Boilerplate: Server-only variables are dynamically fallback-read from
process.envat runtime, meaning they do not need to be manually mapped inside theruntimeEnvparameter.
Quickstart
1. Installation
npm install @arkenv/nextjs arktypepnpm add @arkenv/nextjs arktypeyarn add @arkenv/nextjs arktypebun add @arkenv/nextjs arktype2. 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:
import from "@arkenv/nextjs";
export const = ({
: {
: "string",
},
: {
: "string",
},
: {
: "string",
},
: {
: ..,
: ..,
},
});3. Use in your code
Import env throughout your Next.js application:
import { } from "./env";
// Access is fully typesafe and autocompleted
const apiUrl = .;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:
import { } from "./env";
// Throws a runtime error if evaluated in a client component (during SSR or in the browser)
const dbUrl = .;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:
import from "@arkenv/nextjs";
import { } from "zod";
export const = ({
: {
: .().(),
},
: {
: .().(),
},
: {
: .(["development", "production", "test"]),
},
: {
: ..,
: ..,
},
});