Installation

Install dependencies

Install the package you need depending on your framework:

Core

Includes the core functionality, compatible with any framework:

pnpm add @t3-oss/env-core zod
pnpm add @t3-oss/env-core zod

Next.js

Includes a few preconfigured options for Next.js:

pnpm add @t3-oss/env-nextjs zod
pnpm add @t3-oss/env-nextjs zod

Zod is a required peer dependency for now, but in the future we hope to bring support for any validation library of your choice.

Usage

Create a new file env.ts in your project and define your schema:

src/env.ts
import { createEnv } from "@t3-oss/env-core";
import { z } from "zod";
 
export const env = createEnv({
  clientPrefix: "PUBLIC_",
  server: {
    DATABASE_URL: z.string().url(),
    OPEN_AI_API_KEY: z.string().min(1),
  },
  client: {
    PUBLIC_PUBLISHABLE_KEY: z.string().min(1),
  },
  runtimeEnv: process.env, // or `import.meta.env`, or similar
});
src/env.ts
import { createEnv } from "@t3-oss/env-core";
import { z } from "zod";
 
export const env = createEnv({
  clientPrefix: "PUBLIC_",
  server: {
    DATABASE_URL: z.string().url(),
    OPEN_AI_API_KEY: z.string().min(1),
  },
  client: {
    PUBLIC_PUBLISHABLE_KEY: z.string().min(1),
  },
  runtimeEnv: process.env, // or `import.meta.env`, or similar
});
💡

For frameworks that doesn't support TypeScript configuration files, we recommend using a env.mjs file instead, so you can import it in the configuration file later.

Create your schema

Then, import the env object in your application and use it, taking advantage of type-safety and auto-completion:

some-api-endpoint.ts
import { env } from "~/env"; // On server
 
export const GET = async () => {
  // do fancy ai stuff
  const magic = await fetch("...", {
    headers: { Authorization: env.OPEN_AI_API_KEY },
  });
  // ...
};
some-api-endpoint.ts
import { env } from "~/env"; // On server
 
export const GET = async () => {
  // do fancy ai stuff
  const magic = await fetch("...", {
    headers: { Authorization: env.OPEN_AI_API_KEY },
  });
  // ...
};
some-component.tsx
import { env } from "~/env"; // On client - same import!
 
export const SomeComponent = () => {
  return (
    <SomeProvider publishableKey={env.PUBLIC_PUBLISHABLE_KEY}>
      {/* ... */}
    </SomeProvider>
  );
};
some-component.tsx
import { env } from "~/env"; // On client - same import!
 
export const SomeComponent = () => {
  return (
    <SomeProvider publishableKey={env.PUBLIC_PUBLISHABLE_KEY}>
      {/* ... */}
    </SomeProvider>
  );
};

Further configuration

For more detailed usage intructions, please refer to the documentation of each package: