Nestjs: middleware for all routes except /auth

Viewed 4790

I am started with nestjs recently and i want apply a middleware for all routes, except the auth route.

In the documentation it says that I can add all the controllers or paths of the routes where I want the middleware, but I find this way quite expensive

.forRoutes(
     SearchController,
     Other,
     Other,
     Other
);

So I would like to know if there is a solution, or if you managed to use regex for something like this:

.forRoutes(
    {path: 'All route except /auth', method: RequestMethod.ALL}
);
3 Answers

Nowadays we use the function exclude.

export class YourModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(YourMiddleware)
      .exclude('auth')
      .forRoutes('*');
  }
}

For further: https://docs.nestjs.com/middleware#excluding-routes

DOC: https://docs.nestjs.com/middleware TITLE: Excluding routes

export class AppModule implements NestModule {
      configure(consumer: MiddlewareConsumer) {
        consumer.apply(LoggerMiddleware).forRoutes('*')
        consumer.apply(tokenVerify).exclude('/auth').forRoutes('*')
    } }

Use /auth/(.*) in case you have routes like /auth/login, /auth/register, etc. .

Exclude route referring exact route path.If you have define global prefix at main.ts,It's also need to come in to that exclude path.

Eg :

main.ts

app.setGlobalPrefix('api/v1');

module.ts

export class YourModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(YourMiddleware)
      .exclude({ path:'api/v1/auth',method: RequestMethod.ALL})
      .forRoutes('*');
  }
}
Related