Articles by Sergio Xalambrí

Using Zod to safely read env variables

Zod is a great library to do schema based validations and get fully typed objects as a result. Environment variables are read from process.env but there's no way to truly know if a variable is defined or not with TS, you need to validate at runtime.

Using Zod, it's possible to define any environment variable your app needs and properly type it. First you can create a schema like this one:


import { z } from "zod";

let envSchema = z.object({
  GITHUB_CLIENT_ID: z.string().nonempty(),
  GITHUB_CLIENT_SECRET: z.string().nonempty(),
  STRIPE_API_KEY: z.string().nonempty(),
});

Then you can parse process.env using that schema:

let env = envSchema.parse(process.env);

Zod will ensure the environment variables you defined match the schema and it will remove from the final object any environment variable not defined in the schema. This way your app can't read any other environment variable you didn't explicitly defined.

Finally, export the object or each variable individually and use it in your project.