Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)

like image 723
Abhinandan N.M. Avatar asked May 29 '18 21:05

Abhinandan N.M.


People also ask

What is the use of middleware in NestJS?

Middleware is a function which is called before the route handler. Middleware functions have access to the request and response objects, and the next() middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named next .

Is interceptor a middleware?

In this pa- per we present Interceptor, a middleware-level application segregation and scheduling system that is able to strictly en- force quantitative limitations on node resource usage and, at same time, to make P2P applications achieve satisfactory performance even in face of these limitations.

Does NestJS use Express?

NestJS is platform agnostic - it uses Express by default but you can configure it to work with any HTTP framework like Fastify. It provides a wide range of functionalities, APIs, and libraries so that developers can build applications with fewer lines of code.


1 Answers

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.

like image 69
VinceOPS Avatar answered Sep 19 '22 03:09

VinceOPS