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?
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}');
}
}