Omid Sayfun
Omid SayfunComputer Geek
Home
Notebook
Journey

Online

Github
Linkedin
Hevy
Plyatomic
Notebook
The trap of making everything dynamic
March 01, 2024
A try at type-safe groupBy function in TypeScript
April 10, 2025
Email special headers
November 20, 2024
Adding prettier to eslint
April 10, 2025
Storing Vector in Postgres with Drizzle ORM
March 21, 2024
Upgrading my blog to Next 15
April 05, 2025
Canvas macOS issue
February 20, 2024
tsx doesn’t support decorators
March 26, 2025
Validating NestJS env vars with zod
February 06, 2025
Extending Window: types vs interfaces
March 21, 2025
Loading env file into Node process
February 06, 2025
Add update date field to Postgres
February 27, 2024
Using node API for delay
February 06, 2025
React Component Lifecycle
November 28, 2024
How CQRS is different than Event Sourcing
August 18, 2024
RabbitMQ exchange vs queue
August 14, 2024
PgVector similarity search distance functions
August 13, 2024
PgVector indexing options for vector similarity search
July 31, 2024
Using puppeteer executable for GSTS
June 08, 2024
Why EQ is Your Next Career Upgrade
May 13, 2024
Counting GPT tokens
June 30, 2024
Logging route handler responses in Next.js 14
June 19, 2024
Redirect www subdomain with Cloudflare
June 17, 2024
Logging requests in Express app
June 16, 2024
Move Docker volume to bind mount
June 12, 2024
Next.js Hydration Window Issue
May 29, 2024
Using Git rebase without creating chaos in your repo
May 16, 2024
Implementing RPC Calls with RabbitMQ in TypeScript
March 16, 2024
Optimize webpage load with special tags
March 15, 2024
What the hell is Open Graph?
March 13, 2024
My go-to Next.js ESlint config
March 10, 2024
List of useful Chrome args
March 10, 2024
Combining RxJS observables - Part 1
February 20, 2024

Validating NestJS env vars with zod

February 06, 2025 · Updated on March 21, 2025

Hey there! If you're like me, you probably love using Zod for validating and parsing data objects. It's a lifesaver, right? But when it comes to environment variables (env vars), things can get a bit tricky. You want to parse them as quickly as possible during your application's boot-up phase and then use them confidently throughout your app. That's where NestJS's ConfigModule comes into play.

Setting Up ConfigModule

NestJS provides a handy ConfigModule that lets you register a global module to read your env file and load it into the process. But here's the catch: you need to validate those env vars to ensure they're correct. Luckily, the ConfigModule allows you to register a validate function. Here's a quick look at how you can set it up:

import { ConfigModule } from '@nestjs/config';
 
@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true, validate: /* Your function */ }),
  ]
})
export class AppModule {}

Validating with Zod

The validate function receives the full process.env object and expects a validated, parsed object in return. This is where Zod comes in handy. You can use it to format and validate your env vars like this:

import { z } from "zod";
 








Continue Reading

const
envs
=
z.
object
({
DATABASE_URL: z.string(),
NODE_ENV: z.string().optional(),
});
export const validate = (config: Record<string, unknown>) => {
const validated = envs.parse(config);
return validated;
};

Extending ConfigService Types

As a bonus, you can extend the ConfigService types with your Zod schema. This ensures that whenever you're using the ConfigModule, you have type safety. Here's how you can define your type:

import type { ConfigService } from "@nestjs/config";
 
export type IConfigService = ConfigService<z.infer<typeof envs>>;

Using the Extended ConfigService

Once you've set up your types, you can use them in your modules like so:

@Module({
	imports: [
		DrizzlePostgresModule.registerAsync({
			tag: DB_TAG,
			imports: [ConfigModule],
			inject: [ConfigService],
			useFactory: (configService: IConfigService) => ({
				postgres: {
					url: configService.getOrThrow("DATABASE_URL"),
				},
			}),
		}),
	],
})
export class DbModule {}

tl;dr

  • Use NestJS's ConfigModule to load and validate env vars.
  • Register a validate function to ensure env vars are correct.
  • Use Zod to format and validate env vars.
  • Extend ConfigService types with Zod schema for type safety.
  • Implement the extended types in your modules for better type checking.
  • 02-20-2026

    The trap of making everything dynamic

  • 04-11-2025

    A try at type-safe groupBy function in TypeScript

  • 04-10-2025

    Email special headers

  • 04-10-2025

    Adding prettier to eslint

  • 04-09-2025

    Storing Vector in Postgres with Drizzle ORM