NestJS Zod Config
nestjs-zod-config - NestJS module to load, type and validate configuration using Zod.
Installation
yarn add nestjs-zod-config
Peer dependencies: yarn add @nestjs/common @nestjs/core zod
Setup
-
Have a .env
file in the root of your project.
# .env
PORT=3000
-
Create a config class that extends ZodConfig
and pass it a Zod schema.
import { ZodConfig } from 'nestjs-zod-config';
import { z } from 'zod';
const appConfigSchema = z.object({
HOSTNAME: z.string().min(1).default('0.0.0.0'),
PORT: z.coerce.number().default(3000),
});
export class AppConfig extends ZodConfig(appConfigSchema) {}
-
Register the config class in your module.
import { Module } from '@nestjs/common';
import { ZodConfigModule } from 'nestjs-zod-config';
import { AppConfig } from './app.config';
@Module({
imports: [
ZodConfigModule.forRoot({
service: AppConfig,
}),
],
})
export class AppModule {}
Usage
Use it in your service like this:
import { Injectable } from '@nestjs/common';
import { AppConfig } from './app.config';
@Injectable()
export class AppService {
constructor(private readonly appConfig: AppConfig) {}
getPort(): number {
return this.appConfig.get('PORT');
}
}
or in your main.ts
like this:
import { NestFactory } from '@nestjs/core';
import { AppConfig } from './app.config';
import { AppModule } from './app.module';
const main = async () => {
const app = await NestFactory.create(AppModule);
const appConfig = app.get(AppConfig);
const hostname = appConfig.get('HOSTNAME');
const port = appConfig.get('PORT');
await app.listen(port, hostname);
};
void main();
Testing
yarn test