Skip to main content

Boost Your Env Vars Game with Zod and TypeScript Magic

Zod Logo in blue background.
Last updated: August 17, 2024

#Validating Environment Variables with Zod and TypeScript

Zod is one of the best libraries for handling validation and works seamlessly with TypeScript. In this tutorial, we’ll learn how to use Zod to validate environment variables, providing us with autocomplete and robust TypeScript feedback.

Technologies we’ll use:

you can copy these command in your editor based on your favorite package manager: If your are using npm:

npm
npm i zod dotenv

If your are using yarn:

yarn
yarn add zod dotenv

If your are using pnpm:

pnpm
pnpm add zod dotenv

#Create env.ts file

We’ll create a file called env.ts in your project. This file will contain all the logic for validating your environment variables.

#Implement Zod Schema

The second thing we need to do is create a Zod schema that we’ll use to validate against the environment variables.

env.ts
import dotenv from "dotenv";
import { z } from "zod";
dotenv.config();
const envSchema = z.object({
PORT: z.string().refine(
(value) => {
const port = parseInt(value);
const isPortNumber = !isNaN(port);
const isValidPortRange = port > 0 && port < MAX_PORT_RANGE;
return isPortNumber && isValidPortRange;
},
{
message: "Port is Invalid.",
},
),
});

#Load Environment Variables and Validate Them

Next, we’ll use this schema to validate the environment variables. We can do this using the process.env object provided by Node.js:

env.ts
// code...
type Env = z.infer<typeof envSchema>;
export const ENV: Env = envSchema.parse(process.env);

#Use the Validated Environment Variables

Now that we’ve validated the environment variables, we can export the validated object and use it throughout our application:

exmaple.ts
export const { NODE_ENV, PORT, DATABASE_URL } = validatedEnv;
console.log(NODE_ENV);
Important Note

To fully benefit from these validations, you should only use environment variables from the exported validatedEnv object. If you directly access the process.env object, you won’t benefit from the validation and type safety provided by Zod.