In web development, middleware refers to a function or a set of functions that execute during the lifecycle of a request to the server. It sits between the raw request and the route handler, giving developers the flexibility to perform tasks like logging, authentication, request parsing, and more before the request reaches its intended destination.
In the context of NestJS, middleware functions implement the NestMiddleware
interface, allowing you to add extra logic to your application effortlessly. This is particularly useful for tasks that are common across routes, helping to keep your code DRY (Don't Repeat Yourself).
To create middleware in NestJS, you will typically follow these steps:
Let's build a basic example of a logging middleware that logs incoming requests.
Generate Middleware: Use the NestJS CLI to create the middleware.
nest g middleware logger
Implement the Logger Middleware:
Open the generated logger.middleware.ts
file and implement the logging logic:
import { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() export class LoggerMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { console.log(`Request... Method: ${req.method}, URL: ${req.url}`); next(); // Pass control to the next middleware/route handler } }
In this example, whenever a request comes in, the middleware logs the HTTP method and the request URL.
Apply the Middleware: You can apply the middleware at the module level or simply at the controller level.
app.module.ts
and use the configure
method.import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { LoggerMiddleware } from './logger.middleware'; import { AppController } from './app.controller'; import { AppService } from './app.service'; @Module({ imports: [], controllers: [AppController], providers: [AppService], }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(LoggerMiddleware) .forRoutes('*'); // Apply to all routes } }
If you want the logger to only apply to specific routes, modify the forRoutes
method like this:
consumer.apply(LoggerMiddleware).forRoutes('cats', 'dogs'); // Apply to these specific routes
With this setup, the logging middleware will only log requests made to the routes handling "cats" and "dogs".
Middleware can be leveraged for various tasks in a NestJS application:
Here's a quick example of an authentication middleware:
import { Injectable, NestMiddleware, HttpException, HttpStatus } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() export class AuthMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { const token = req.headers['authorization']; if (!token) { throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED); } // Logic to verify token (omitted for brevity) next(); } }
The flexibility of middleware in NestJS allows developers to inject powerful functionality into their applications effortlessly. By understanding how to create and use middleware effectively, you can enhance the capabilities of your NestJS application, making it more robust and maintainable. Whether you're logging requests, enforcing authentication, or managing errors, middleware is an indispensable tool in your NestJS development arsenal. Explore and experiment with middleware in your next NestJS project, and watch how it streamlines your workflow.
Embrace the versatility of middleware to take your application to the next level!
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS