This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Feature | Purpose | Execution Timing | Common Use Case | |
---|---|---|---|---|
Middleware | Modifies incoming requests (e.g., logging, CORS) | Before reaching the controller | Logging, modifying headers, request transformations | |
Guards | Controls access based on authentication or roles | Before executing the controller logic | Role-based access, authentication checks | |
Interceptors | Modifies or transforms responses (e.g., logging, caching) | After controller processing | Response formatting, performance monitoring, error handling |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Module } from '@nestjs/common'; | |
import { ConfigModule } from '@nestjs/config'; | |
import * as Joi from 'joi'; | |
@Module({ | |
imports: [ | |
ConfigModule.forRoot({ | |
isGlobal: true, // Makes config available across the app | |
envFilePath: `.env.${process.env.NODE_ENV || 'development'}`, // Load specific .env file based on NODE_ENV | |
ignoreEnvFile: process.env.NODE_ENV === 'production', // Ignore .env in production (use external env variables) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// accessing env variables securely | |
import { Injectable } from '@nestjs/common'; | |
import { ConfigService } from '@nestjs/config'; | |
@Injectable() | |
export class AppService { | |
constructor(private configService: ConfigService) {} | |
getDatabaseUrl(): string { | |
return this.configService.get<string>('DATABASE_URL'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// app.module.ts | |
import { Module } from '@nestjs/common'; | |
import { ConfigModule } from '@nestjs/config'; | |
@Module({ | |
// loads default .env file present in project directory | |
imports: [ConfigModule.forRoot()], | |
}) | |
export class AppModule {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, HttpException, HttpStatus } from '@nestjs/common'; | |
import { Observable } from 'rxjs'; | |
import { catchError } from 'rxjs/operators'; | |
@Injectable() | |
export class ErrorHandlingInterceptor implements NestInterceptor { | |
intercept(context: ExecutionContext, next: CallHandler): Observable<any> { | |
return next.handle().pipe( | |
catchError(err => { | |
throw new HttpException('Something went wrong', HttpStatus.INTERNAL_SERVER_ERROR); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller, Get, UseInterceptors } from '@nestjs/common'; | |
import { LoggingInterceptor } from './logging.interceptor'; | |
import { TransformInterceptor } from './transform.interceptor'; | |
@Controller('users') | |
@UseInterceptors(LoggingInterceptor, TransformInterceptor) //applying multiple interceptors | |
export class UsersController { | |
@Get() | |
findAll() { | |
return { name: 'John Doe', age: 30 }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; | |
import { Observable } from 'rxjs'; | |
import { map } from 'rxjs/operators'; | |
@Injectable() | |
export class TransformInterceptor implements NestInterceptor { | |
intercept(context: ExecutionContext, next: CallHandler): Observable<any> { | |
return next.handle().pipe( | |
map(data => ({ | |
success: true, |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// app.module.ts | |
import { Module } from '@nestjs/common'; | |
import { APP_INTERCEPTOR } from '@nestjs/core'; | |
import { LoggingInterceptor } from './logging.interceptor'; | |
@Module({ | |
providers: [ | |
{ | |
provide: APP_INTERCEPTOR, | |
useClass: LoggingInterceptor, |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// main.ts | |
import { NestFactory } from '@nestjs/core'; | |
import { AppModule } from './app.module'; | |
import { LoggingInterceptor } from './logging.interceptor'; | |
import { APP_INTERCEPTOR } from '@nestjs/core'; | |
async function bootstrap() { | |
const app = await NestFactory.create(AppModule); | |
app.useGlobalInterceptors(new LoggingInterceptor()); // Apply globally | |
await app.listen(3000); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller, Get, UseInterceptors } from '@nestjs/common'; | |
import { LoggingInterceptor } from './logging.interceptor'; | |
@Controller('users') | |
@UseInterceptors(LoggingInterceptor) // Apply to all routes in this controller | |
export class UsersController { | |
@Get() | |
findAll() { | |
return { message: 'List of users' }; | |
} |
NewerOlder