NestJs using middleware on all routes

Viewed 1478

I'm new to nestjs, and I'm using a middleware to authenticate my users. I would like to apply that for all routes. I'm currently adding controller one by one and it's becoming redundant.

export class AppModule implements NestModule {
  public configure(consumer: MiddlewareConsumer): void {
    consumer.apply(GetUserMiddleware).forRoutes(
      UserController,
      //***
    );
  }
}

I've surfed the documentation and could not find it (NestJs - Middleware).

How can I change this to get my middleware to work on all routes?

4 Answers
import { RequestMethod } from '@nestjs/common';
// ...
      .forRoutes({
        path: '*',
        method: RequestMethod.ALL,
      });

1st Method:
If you want to use your middleware on every route you can use global middleware.

const app = await NestFactory.create(AppModule);
app.use(yourMiddlewareMethod);
await app.listen(3000);

NOTE: Though this would work for every route so the user won't be able to login. In this case, you can override the usage of middleware on your user module by excluding it in app.module.ts like this

consumer
  .apply(yourMiddlewareMethod)
  .exclude(
    { path: 'yourPath', method: RequestMethod.GET },
    { path: 'yourPath', method: RequestMethod.POST },
    'yourPath/(.*)',
  )
  .forRoutes(yourController);

2nd Method:
In app.module.ts :

...
    export class AppModule implements NestModule {
      configure(consumer: MiddlewareConsumer) {
        consumer
          .apply(yourMiddlewareMethod)
          .forRoutes(yourController);
      }
    }

Hope this answers your question.

Just by using '*' in for routes:

export class AppModule implements NestModule {
  public configure(consumer: MiddlewareConsumer): void {
    consumer.apply(GetUserMiddleware).forRoutes('*');
  }
}

This is how I achieved it. All work is done in StProxyService.

import { createProxyMiddleware } from 'http-proxy-middleware';
import { StProxyService } from './st-proxy.service';
import { StProxyController } from './st-proxy.controller';

export class StProxyModule implements NestModule {
  constructor(private readonly stProxyyService: StProxyService) {}

  configure(consumer: MiddlewareConsumer) {
    const stProxyMiddleware =
      createProxyMiddleware(this.stProxyyService.getDefaultOptions());
    consumer
      .apply(stProxyMiddleware)
      .forRoutes(StProxyController);
  }
}
@Controller('st-proxy')
export class StProxyController {
  @All('*')
  noopAction(): string {
    return 'This action is no operation';
  }
}
Related