Understanding NestJS Middleware

Middleware in NestJS is a powerful tool that allows you to execute functions before reaching the route handlers. Middleware functions have access to the request and response objects and can perform tasks such as authentication, logging, and validation….


This content originally appeared on DEV Community and was authored by Osarugue Enehizena

Middleware in NestJS is a powerful tool that allows you to execute functions before reaching the route handlers. Middleware functions have access to the request and response objects and can perform tasks such as authentication, logging, and validation. Here's a detailed tutorial based on the provided timestamp.

Step-by-Step Guide

1. Understanding Middleware:

  • Middleware functions are executed before the route handler.
  • Common uses include checking authentication tokens, logging requests, and modifying request/response objects.
  • Middleware has access to request, response, and next objects.

2. Setting Up Middleware:

  • Middleware can be created manually or using the NestJS CLI.
  • Example using CLI:

    nest generate middleware users/middlewares/example
    
  • This generates the necessary middleware files.

3. Middleware Implementation:

  • Open the generated middleware file (e.g., example.middleware.ts).
  • Modify the class to include necessary logic:

    import { Injectable, NestMiddleware } from '@nestjs/common';
    import { Request, Response, NextFunction } from 'express';
    
    @Injectable()
    export class ExampleMiddleware implements NestMiddleware {
      use(req: Request, res: Response, next: NextFunction) {
        console.log('ExampleMiddleware');
        next();
      }
    }
    
    

4. Registering Middleware:

  • Open the module where you want to apply the middleware (e.g., users.module.ts).
  • Implement the NestModule interface and configure the middleware:

    import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
    import { ExampleMiddleware } from './middlewares/example.middleware';
    
    @Module({
      // ... other module metadata
    })
    export class UsersModule implements NestModule {
      configure(consumer: MiddlewareConsumer) {
        consumer
          .apply(ExampleMiddleware)
          .forRoutes('users');
      }
    }
    
    
  • The middleware will be applied to all routes starting with users.

5. Adding More Middleware:

  • Create another middleware using CLI or manually:

    nest generate middleware users/middlewares/another
    
    
  • Modify the class (e.g., another.middleware.ts):

    import { Injectable, NestMiddleware } from '@nestjs/common';
    import { Request, Response, NextFunction } from 'express';
    
    @Injectable()
    export class AnotherMiddleware implements NestMiddleware {
      use(req: Request, res: Response, next: NextFunction) {
        console.log('AnotherMiddleware');
        next();
      }
    }
    
    
  • Register both middleware in the module:

    import { AnotherMiddleware } from './middlewares/another.middleware';
    
    @Module({
      // ... other module metadata
    })
    export class UsersModule implements NestModule {
      configure(consumer: MiddlewareConsumer) {
        consumer
          .apply(ExampleMiddleware, AnotherMiddleware)
          .forRoutes('users');
      }
    }
    
    

6. Conditional Middleware Execution:

  • Apply middleware to specific routes and methods:

    //users.module.ts
    import { RequestMethod } from '@nestjs/common';
    
    @Module({
      // ... other module metadata
    })
    export class UsersModule implements NestModule {
      configure(consumer: MiddlewareConsumer) {
        consumer
          .apply(ExampleMiddleware)
          .forRoutes({ path: 'users', method: RequestMethod.GET });
    
        consumer
          .apply(AnotherMiddleware)
          .forRoutes({ path: 'users/:id', method: RequestMethod.POST });
      }
    }
    
    

7. Adding Logic to Middleware:

  • Middleware can perform tasks like checking headers or throwing exceptions:

    //example.middleware.ts
    import { HttpException, HttpStatus } from '@nestjs/common';
    
    @Injectable()
    export class ExampleMiddleware implements NestMiddleware {
      use(req: Request, res: Response, next: NextFunction) {
        const authHeader = req.headers['authorization'];
        if (!authHeader) {
          throw new HttpException('No authorization token', HttpStatus.FORBIDDEN);
        }
        if (authHeader !== 'correct_token') {
          throw new HttpException('Invalid authorization token', HttpStatus.FORBIDDEN);
        }
        next();
      }
    }
    
    

8. Testing Middleware:

  • Ensure your middleware works by making requests to the routes and checking logs or responses.

9. Documentation and Further Learning:

  • Refer to the NestJS documentation for more details on middleware, including advanced topics and best practices.

This guide should help you get started with middleware in NestJS, providing a foundation for implementing various middleware functions to enhance your application.

Middleware Image from NestJs Documentation


This content originally appeared on DEV Community and was authored by Osarugue Enehizena


Print Share Comment Cite Upload Translate Updates
APA

Osarugue Enehizena | Sciencx (2024-07-22T02:24:32+00:00) Understanding NestJS Middleware. Retrieved from https://www.scien.cx/2024/07/22/understanding-nestjs-middleware/

MLA
" » Understanding NestJS Middleware." Osarugue Enehizena | Sciencx - Monday July 22, 2024, https://www.scien.cx/2024/07/22/understanding-nestjs-middleware/
HARVARD
Osarugue Enehizena | Sciencx Monday July 22, 2024 » Understanding NestJS Middleware., viewed ,<https://www.scien.cx/2024/07/22/understanding-nestjs-middleware/>
VANCOUVER
Osarugue Enehizena | Sciencx - » Understanding NestJS Middleware. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/22/understanding-nestjs-middleware/
CHICAGO
" » Understanding NestJS Middleware." Osarugue Enehizena | Sciencx - Accessed . https://www.scien.cx/2024/07/22/understanding-nestjs-middleware/
IEEE
" » Understanding NestJS Middleware." Osarugue Enehizena | Sciencx [Online]. Available: https://www.scien.cx/2024/07/22/understanding-nestjs-middleware/. [Accessed: ]
rf:citation
» Understanding NestJS Middleware | Osarugue Enehizena | Sciencx | https://www.scien.cx/2024/07/22/understanding-nestjs-middleware/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.