Yes! Exactly! Yesterday, after seeing how to pass parameters to Middleware functions in NestJS, I tried the same with Guards but it was not working well, I was getting compiler errors. I went to look into the source code of AuthGuard
and found it follows a “factory” / “mixin” pattern. The key is using a mixin
methods from @nestjs/common
that I can’t find documentation on. So, I got it working now.
There are a few things in NestJS that help with common Express patterns but that are not documented.
My new version of this tutorial that I submitted for review is…
- Dropping Passport.
- Use an
AuthGuard
instead that verifies the access token present in the request. - Dropping decorator.
- Use a
PermissionsGuard
that takes as argument the permissions the route requires. - Testing the API without using a client frontend-application
Adios, WAB Dashboard
- Use
ConfigService
instead ofdotenv
/process.env
to access.env
variables.
I feel that using Middleware for both authorization and permissions checking ends up becoming a not-so-good developer experience as now you have to bloat up a Nest module with protection logic and maintain two files: module and controller. If you look at the controller, you wouldn’t know if an endpoint is protected, you’d have to find the middleware for the path.
Instead of doing that, you can have the same contextual information and function by using Guards on the controller or endpoint.