Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/alxevvv/nest-zod-config
Define NestJS configuration with validation and type safety using zod
https://github.com/alxevvv/nest-zod-config
config configuration dotenv nest nestjs typescript zod
Last synced: about 15 hours ago
JSON representation
Define NestJS configuration with validation and type safety using zod
- Host: GitHub
- URL: https://github.com/alxevvv/nest-zod-config
- Owner: alxevvv
- License: mit
- Created: 2023-07-08T22:22:02.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2023-11-01T08:52:30.000Z (about 1 year ago)
- Last Synced: 2024-10-12T18:21:42.520Z (about 1 month ago)
- Topics: config, configuration, dotenv, nest, nestjs, typescript, zod
- Language: TypeScript
- Homepage:
- Size: 93.8 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# nest-zod-config
Define NestJS configuration with validation and type safety using zod
## Install
```
npm install zod nest-zod-config
```If you want to load configuration from `.env` file, also install
[dotenv](https://github.com/motdotla/dotenv) package:```
npm install dotenv
```## Example
```properties
# .envport=3000
str=something
```### Usage in NestJS module
```typescript
// app.config.tsimport { Config } from 'nest-zod-config';
import { z } from 'zod';const appConfigSchema = z.object({
port: z.number(),
str: z.string(),
});export class AppConfig extends Config(appConfigSchema) {}
``````typescript
// app.service.tsimport { Injectable } from '@nestjs/common';
import { AppConfig } from './app.config';
@Injectable()
export class AppService {
constructor(private readonly config: AppConfig) {}someMethod() {
// `this.config` now contains your configuration with types:
// { port: 3000, str: 'something' }
}
}
``````typescript
// app.module.tsimport { ZodConfigModule, dotEnvLoader } from 'nest-zod-config';
import { AppConfig } from './app.config';
import { AppService } from './app.service';@Module({
imports: [
ZodConfigModule.forRootAsync({
config: AppConfig,
loader: dotEnvLoader(),
}),
],
providers: [AppService],
})
export class AppModule {}
```### Usage outside of NestJS modules
For example in the `bootstrap` function before application creation:
```typescript
// main.tsimport { NestFactory } from '@nestjs/core';
import { dotEnvLoader, loadConfig } from 'nest-zod-config';
import { AppModule } from './app.module';
import { AppConfig } from './app.config';async function bootstrap() {
const config = await loadConfig(AppConfig, dotEnvLoader());
const app = await NestFactory.create(AppModule);
await app.listen(config.PORT);
}bootstrap();
```## License
Licensed under the MIT license. Copyright (c) 2023-present Vladislav Alexeev