'How to pass parameters to the use function inside the middleware when consuming the middleware in Nest js

How can i pass parameters from here

export class NotificationModule implements NestModule{
  public configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddleware).forRoutes(
        {path: 'notification/create', method: RequestMethod.POST},

And How can I use passed parameters in here

@Injectable()
export class AuthMiddleware implements NestMiddleware {
    constructor(private readonly studentService: StudentService) {
    }

    async use(req: Request, res: Response, next: NextFunction) {
       ????????
    }


Solution 1:[1]

I think you can use mixin pattern here, so solution migth look like

module

export class NotificationModule implements NestModule{
  public configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddlewareCreator({ value: true })).forRoutes(
        {path: 'notification/create', method: RequestMethod.POST},

and mixin

import { Injectable, mixin, NestMiddleware, Type } from '@nestjs/common';
...
export function AuthMiddlewareCreator(options: AuthMiddlewareOptions): Type<NestMiddleware> {

    @Injectable()
    class AuthMiddleware implements NestMiddleware {
      constructor(private readonly studentService: StudentService) {
      }

      async use(req: Request, res: Response, next: NextFunction) {
        // you can use options here, for example
        const { value } = options;
       ...
     }
  }
  return mixin(AuthMiddleware);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aleksey Malashenok