typescript
50 lines · 6 steps
Validated, typed config in NestJS
A NestJS module validates environment variables at startup with Joi and exposes them through a typed, injectable service.
Explained by
highlit
1import { Module, Injectable } from '@nestjs/common';
2import { ConfigModule, ConfigService } from '@nestjs/config';
3import * as Joi from 'joi';
4
5const validationSchema = Joi.object({
6 NODE_ENV: Joi.string().valid('development', 'production', 'test').default('development'),
7 PORT: Joi.number().default(3000),
8 DATABASE_URL: Joi.string().uri().required(),
9 JWT_SECRET: Joi.string().min(32).required(),
10 JWT_EXPIRES_IN: Joi.string().default('3600s'),
11});
12
13@Module({
14 imports: [
15 ConfigModule.forRoot({
16 isGlobal: true,
17 cache: true,
18 envFilePath: [`.env.${process.env.NODE_ENV ?? 'development'}`, '.env'],
19 validationSchema,
20 validationOptions: { abortEarly: false },
21 }),
22 ],
23 providers: [AppConfigService],
24 exports: [AppConfigService],
25})
26export class AppConfigModule {}
27
28@Injectable()
29export class AppConfigService {
30 constructor(private readonly config: ConfigService) {}
31
32 get isProduction(): boolean {
33 return this.config.getOrThrow<string>('NODE_ENV') === 'production';
34 }
35
36 get port(): number {
37 return this.config.getOrThrow<number>('PORT');
38 }
39
40 get databaseUrl(): string {
41 return this.config.getOrThrow<string>('DATABASE_URL');
42 }
43
44 get jwt(): { secret: string; expiresIn: string } {
45 return {
46 secret: this.config.getOrThrow<string>('JWT_SECRET'),
47 expiresIn: this.config.getOrThrow<string>('JWT_EXPIRES_IN'),
48 };
49 }
50}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Validating env vars at boot turns silent misconfiguration into a loud, immediate failure.
- 2Wrapping ConfigService in a typed service gives the rest of the app safe, autocompleted access to settings.
- 3Marking the config module global lets every feature read configuration without re-importing it.
Related explainers
java
@Component public class RegionCacheWarmer implements SmartInitializingSingleton { private static final Logger log = LoggerFactory.getLogger(RegionCacheWarmer.class);
Warming a Spring cache at startup
caching
startup-hook
dependency-injection
Intermediate
7 steps
typescript
import { Controller, Param, Sse, MessageEvent } from '@nestjs/common'; import { Observable, interval, merge } from 'rxjs'; import { filter, map, takeWhile } from 'rxjs/operators'; import { JobService } from './job.service';
Streaming job progress with SSE in NestJS
server-sent-events
reactive-streams
rxjs
Intermediate
8 steps
java
public final class EmailNormalizer { private static final Pattern EMAIL_PATTERN = Pattern.compile( "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
Normalizing email addresses in Java
validation
regex
normalization
Intermediate
8 steps
typescript
import { Controller, All, Req,
Catch-all routes and error shaping in NestJS
exception-handling
routing
middleware
Intermediate
6 steps
python
from datetime import date, timedelta from typing import Annotated from fastapi import APIRouter, Depends, Query
Validating date ranges with FastAPI dependencies
dependency-injection
validation
pydantic
Intermediate
6 steps
typescript
import { ArgumentsHost, Catch, ConflictException,
Turning TypeORM lock errors into 409s in NestJS
exception-handling
optimistic-locking
http-status
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/validated-typed-config-in-nestjs-explained-typescript-2db5/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.