Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to apply a middleware for all routes (globally)? #543

Closed
weeco opened this issue Apr 5, 2018 · 13 comments
Closed

Is it possible to apply a middleware for all routes (globally)? #543

weeco opened this issue Apr 5, 2018 · 13 comments

Comments

@weeco
Copy link

@weeco weeco commented Apr 5, 2018

I'd like to apply a middleware for all routes, but apparently the forRoutes() config is needed. Is there a way to apply the middleware for all routes in the app.module ?

My use case is the JWT authentication for a REST Api which should be active for all endpoints.

export class AppModule {
  configure(consumer: MiddlewaresConsumer) {
    consumer.apply(AuthMiddleware);
  }
}
@ericzon

This comment has been minimized.

Copy link

@ericzon ericzon commented Apr 5, 2018

Hello weeco, if you pass a controller class in forRoutes, it'll be applied to all is routes.

@Mesko89

This comment has been minimized.

Copy link

@Mesko89 Mesko89 commented Apr 5, 2018

You can also use forRoutes({ path: '*', method: RequestMethod.ALL }):

export class AppModule {
  configure(consumer: MiddlewaresConsumer): void {
    consumer
      .apply([AuthMiddleware])
      .with('AppModule')
      .forRoutes({ path: '*', method: RequestMethod.ALL });
  }
}
@weeco

This comment has been minimized.

Copy link
Author

@weeco weeco commented Apr 5, 2018

Using the wildcard for the path works. Thanks!

@lazarljubenovic

This comment has been minimized.

Copy link

@lazarljubenovic lazarljubenovic commented Nov 6, 2018

Apparently, simply passing an asterisk * (instead of a full object) works as well, for all methods (I think).

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

This comment has been minimized.

Copy link

@yharaskrik yharaskrik commented Nov 6, 2018

You can also do:

const app = await NestFactory.create(ApplicationModule);
app.use(logger);
await app.listen(3000);

https://docs.nestjs.com/middleware

@careuno

This comment has been minimized.

Copy link

@careuno careuno commented Nov 11, 2018

You can also do:

const app = await NestFactory.create(ApplicationModule);
app.use(logger);
await app.listen(3000);

https://docs.nestjs.com/middleware

But if you have a Nest middleware, it throw an error. For example I got this:
Class constructor HelmetMiddleware cannot be invoked without 'new'

And not really it is going to work invoking it with 'new'

@ChristopherKiss

This comment has been minimized.

Copy link

@ChristopherKiss ChristopherKiss commented Dec 2, 2018

@careuno,

You need to use functional middleware when using app.use();

https://docs.nestjs.com/middleware

export function logger(req, res, next) {
  console.log(`Request...`);
  next();
};
import logger from 'src/middleware/logger';

...

const app = await NestFactory.create(ApplicationModule);
app.use(logger);
await app.listen(3000);
@felangel

This comment has been minimized.

Copy link

@felangel felangel commented Mar 12, 2019

This seems like it's no longer working in v5.7.4 😢

@vijayakumar-psg587

This comment has been minimized.

Copy link

@vijayakumar-psg587 vijayakumar-psg587 commented Mar 14, 2019

I myself wanted to use busboy body parser middleware, but unsure how that can be done in nestjs. Any ideas.? app.use(busboybodyParser()); doesn't work My nest version is 5.8.0

@felixhayashi

This comment has been minimized.

Copy link

@felixhayashi felixhayashi commented Jul 17, 2019

You need to use functional middleware when using app.use();

this should definitely be documented...

@kamilmysliwiec

This comment has been minimized.

Copy link
Member

@kamilmysliwiec kamilmysliwiec commented Jul 17, 2019

this should definitely be documented...

It is documented

@felixhayashi

This comment has been minimized.

Copy link

@felixhayashi felixhayashi commented Jul 21, 2019

Hi @kamilmysliwiec,

thanks for your reply.

The section regarding global middlewares does not include a note about that only functional middlewares are possible on a "global" level.

2019-07-21 08:40:55

I would recommend to add: "Accessing the DI container in a global middleware is not possible, you need to use a functional middleware instead when using app.use();"

The section about functional middlewares also does not conatin such a hint. Maybe it could be extended to:

Consider using the simpler functional middleware alternative any time your middleware doesn't need any dependencies or if you need to register the middleware as global middleware.

Finally, in the section about DI it starts of with the claim:

Nest middleware fully supports Dependency Injection.

Which does not seem to be true for global middlewares.

The only part I found where it is implicitly communicated, that DI is impossible for global DI is this part in the section about DI.

Just as with providers and controllers, they are able to inject dependencies that are available within the same module. As usual, this is done through the constructor

May I ask, whether you ever considered also making the services, that are publicly exposed by the different modules via providers, available to global middlewares via DI?

Anyhow, the .forRoutes('*') technique to listen to all requests works fine for me now.

Offtopic: thanks for the great framwork, it is great to see somebody being dedicated to the idea of improving the architecture of nodejs backends 👍

@lock

This comment has been minimized.

Copy link

@lock lock bot commented Oct 19, 2019

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.

@lock lock bot locked as resolved and limited conversation to collaborators Oct 19, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
You can’t perform that action at this time.