Abhinandan N.M.
Abhinandan N.M.

Reputation: 372

How to use a route specific middleware of express in Nestjs?

I'm trying to use this library (keycloak-connect) for authentication and authorization. It has a global middleware that can be directly used by app.use() method or by wrapping a nestjs middlewareclass around it. But how to use the route specific express middleware which is used to protect individual routes?.

Example usage in plain express app

app.get( '/protected', keycloak.protect('adminRole'), handler );

The protect method returns a plain express middleware with signature function(req, res, next)

Upvotes: 11

Views: 23083

Answers (2)

Kshateesh
Kshateesh

Reputation: 609

In case you only want your middleware to be applied on the routes in a controller, you may -

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

Upvotes: 1

VinceOPS
VinceOPS

Reputation: 2720

Your "handler" is a method (decorated with either GET, or POST, etc) in a class decorated with @Controller. The module importing this controller is supposed to declare the middleware.

Example:

@Module({
  controllers: [YourController],
})
export class YourModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(keyCloack.protect('adminRole'))
      .forRoutes('/protected');
  }
}

Where YourController contains the handler for the route '/protected'.

Implementing NestModule is the key. Then you're obliged to declare configure and can use the consumer.

Upvotes: 15

Related Questions