T3 Env

Framework agnostic validation for type-safe environment variables

README

Typesafe Envs made Simple


Deploying your app with invalid environment variables is a hassle. This package helps you to avoid that.

Installation


  1. ```bash
  2. # Core package, no framework specific features
  3. pnpm add @t3-oss/env-core zod
  4. # or, with options preconfigured for Next.js
  5. pnpm add @t3-oss/env-nextjs zod
  6. ```

Currently only supports Zod (which you'll need to install separately). Bring your own validation library is on the roadmap.


Usage


For full documentation, see https://env.t3.gg


This package supports the full power of Zod, meaning you can use transforms and default values.

Define your schema


  1. ```ts
  2. // src/env.mjs
  3. import { createEnv } from "@t3-oss/env-nextjs";
  4. import { z } from "zod";

  5. export const env = createEnv({
  6.   /*
  7.    * Serverside Environment variables, not available on the client.
  8.    * Will throw if you access these variables on the client.
  9.    */
  10.   server: {
  11.     DATABASE_URL: z.string().url(),
  12.     OPEN_AI_API_KEY: z.string().min(1),
  13.   },
  14.   /*
  15.    * Environment variables available on the client (and server).
  16.    *
  17.    * 💡 You'll get typeerrors if these are not prefixed with NEXT_PUBLIC_.
  18.    */
  19.   client: {
  20.     NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: z.string().min(1),
  21.   },
  22.   /*
  23.    * Due to how Next.js bundles environment variables on Edge and Client,
  24.    * we need to manually destructure them to make sure all are included in bundle.
  25.    *
  26.    * 💡 You'll get typeerrors if not all variables from `server` & `client` are included here.
  27.    */
  28.   runtimeEnv: {
  29.     DATABASE_URL: process.env.DATABASE_URL,
  30.     OPEN_AI_API_KEY: process.env.OPEN_AI_API_KEY,
  31.     NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY:
  32.       process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,
  33.   },
  34. });
  35. ```

Use said schema in your app with autocompletion and type inference


  1. ```ts
  2. // src/app/hello/route.ts
  3. import { env } from "../env.mjs";

  4. export const GET = (req: Request) => {
  5.   const DATABASE_URL = env.DATABASE_URL;
  6.   // use it...
  7. };
  8. ```

Roadmap


- [ ] Bring your own validation library - currently only supports Zod.