📜  nestjs forRoutes middlewarwe - Javascript (1)

📅  最后修改于: 2023-12-03 15:03:09.635000             🧑  作者: Mango

NestJS forRoutes Middleware - JavaScript

NestJS forRoutes middleware is a powerful tool that allows developers to execute custom code before or after the main routing logic. This can be useful for various purposes including authentication, logging, exception handling, and more.

Usage

To use forRoutes middleware in NestJS, you first have to create a middleware function. A middleware function is a function that takes three parameters - req, res, and next - and performs a certain action. You can then use app.use() or route.use() to apply the middleware function to your application or routes.

Here is an example of how to create and use a middleware function in NestJS:

// custom.middleware.js
export function myMiddleware(req, res, next) {
  console.log('Executing my middleware...');
  next();
}

// app.module.js
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { myMiddleware } from './custom.middleware';

@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(myMiddleware)
      .forRoutes('*') // apply middleware to all routes
  }
}

In this example, we create a middleware function called myMiddleware that simply logs a message to the console. We then apply this middleware function to all routes by calling .forRoutes('*').

Multiple Middleware Functions

It's also possible to apply multiple middleware functions to a single route or to a group of routes. You can do this by chaining the .apply() method multiple times. The middleware functions will be executed in the order in which they are added.

// auth.middleware.js
export function authMiddleware(req, res, next) {
  console.log('Authenticating user...');
  next();
}

// logger.middleware.js
export function loggerMiddleware(req, res, next) {
  console.log(`[${new Date().toISOString()}] Request received: ${req.method} ${req.url}`);
  next();
}

// app.module.js
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { authMiddleware } from './auth.middleware';
import { loggerMiddleware } from './logger.middleware';

@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(authMiddleware, loggerMiddleware)
      .forRoutes('/api/*')
  }
}

In this example, we create two middleware functions - authMiddleware and loggerMiddleware - and apply them to all routes that match the pattern /api/*. The authMiddleware function authenticates the user, while the loggerMiddleware function logs the details of the incoming request.

Conclusion

NestJS forRoutes middleware is a powerful tool that can be used to implement custom logic before or after the routing process. By creating custom middleware functions, you can easily add features such as authentication, logging, and error handling to your application.