Skip to content

Instantly share code, notes, and snippets.

View Vatsalya-singhi's full-sized avatar

Vatsalya Singhi Vatsalya-singhi

View GitHub Profile
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
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)
// 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');
// 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 {}
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);
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 };
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,
// 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,
// 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);
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' };
}