Nest: Apply middleware to all routes

Created on 18 Aug 2017  路  12Comments  路  Source: nestjs/nest

Is it possible to use middleware function for all routes?

In express.js you can quickly achieve this by applying function to the application's use method:

app.use(function (req, res, next) {
 // do whatever you like
  next();
});

Most helpful comment

I have configured it in the application module

@Module({
  modules: [
    CategoryModule,
    AuthModule
  ]
})
export default class ApplicationModule {
  configure(consumer: MiddlewaresConsumer) {
    consumer.apply(AuthMiddleware)
      .forRoutes({
        path: '*', method: RequestMethod.ALL
      });
  }
}

And it applies middleware function to all routes in the application

All 12 comments

Hey ! yes of course,
in the *.module.ts you can add the following things

export class UsersModule {
    configure(consumer: MiddlewaresConsumer) {
            consumer.apply(AuthMiddleware).forRoutes(YourController);
    }
}

that apply the middleware for all routes in the controller.

_...that apply the middleware for all routes in the controller._

You need to list the controllers that you want to apply middleware function to (if you add new controller it need to be added to that list)

But is there a way to apply middleware function on all the routes of every controller in nest app?

Ok sorry for the miss understanding, in this case you can use instance.all('*', YourMiddleWare)
That's apply it on all incoming route path whatever the method used(GET, POST, PUT, ...)

const instance = express();
instance.all('*', MiddleWare);
const app = NestFactory.create(ApplicationModule, instance);

So as I can see it can be achieved using express instance outside nest app

thanks @adrien2p

@adrien2p

I have not noticed this in the documentation. You can also achieve this by defining the path for which the middleware function should by applied like this:

consumer.apply(AuthMiddleware).forRoutes({ 
    path: '*', method: RequestMethod.ALL 
});

Yes you can do this but i dont know if it's apply in all route app, may be in the applicationModule that could works

I have configured it in the application module

@Module({
  modules: [
    CategoryModule,
    AuthModule
  ]
})
export default class ApplicationModule {
  configure(consumer: MiddlewaresConsumer) {
    consumer.apply(AuthMiddleware)
      .forRoutes({
        path: '*', method: RequestMethod.ALL
      });
  }
}

And it applies middleware function to all routes in the application

Is it possible to run middleware for all routes except for one? For example, I want to run authorization on all routes except for the one that handles the initial authentication request.

@adammfrank this same was recommended in #17 since April
check this, I think this would be very useful

public resolve() {
return async (req, res, next) => {
if (req.headers.authorization ){
const token = req.headers.authorization;
const decoded: any =passport.authenticate(token, process.env.JWT_KEY || '');
console.log(decoded)

};
next();

}
}

` public resolve() {
return async (req, res, next) => {
if (req.headers.authorization ){
const token = req.headers.authorization;
const decoded: any =passport.authenticate(token, process.env.JWT_KEY || '');
console.log(decoded)

};
next();

}`

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings