Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJs using middleware on all routes

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?

like image 552
BingBong Avatar asked Oct 19 '25 03:10

BingBong


1 Answers

Just by using '*' in forRoutes():

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

EDIT (2025-02-24):

The new version Nestjs 11 (Express v5) define wildcard differently, you should now use '{*splat}' in forRoutes():

export class AppModule implements NestModule {
  public configure(consumer: MiddlewareConsumer): void {
    consumer.apply(GetUserMiddleware).forRoutes('{*splat}');
  }
}
like image 138
Leccho Avatar answered Oct 21 '25 12:10

Leccho