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
, andnext
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.
Top comments (0)