Socket
Socket
Sign inDemoInstall

nestjs-zod-config

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nestjs-zod-config

NestJS module to load, type and validate configuration using Zod


Version published
Weekly downloads
93
increased by25.68%
Maintainers
1
Weekly downloads
 
Created
Source

NestJS Zod Config

NPM version NPM downloads Fastify

nestjs-zod-config - NestJS module to load, type and validate configuration using Zod.

Installation

yarn add nestjs-zod-config

Setup

  1. Have a .env file in the root of your project.

    # .env
    PORT=3000
    
  2. Create a config class that extends ZodConfig and pass it a Zod schema.

    // app.config.ts
    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) {}
    
  3. Register the config class in your module.

    // app.module.ts
    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:

// app.service.ts
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:

// main.ts
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

Keywords

FAQs

Package last updated on 14 Jan 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc