#Exporting a Guard from a module

3 messages · Page 1 of 1 (latest)

solemn palm
#

If I export a guard from a module, and import that module elsewhere, I find that NestJs cannot resolve the dependencies of the guard. In contrast, exporting a service, Nest is able to resolve the dependencies.

Is there some reason why guards are treated differently by the DI system? Is there some workaround?

dreamy storm
#

Guards (and other enhancers) are not actually provided by a module (you don't put them in providers, nor can you export them (well, if you do, then it does nothing, really)). They don't belong to any module at all - they bind to Controllers that are a part of some module. And they look for dependencies in the module in which they're used.

That means, if a Guard needs dependencies from module B, but is used in Module B, then Module A must be imported there, and the dependencies it needs must be exported from Module A.

I know it's not very intuitive, but that's how it works.

solemn palm
#

okay, thanks, that's really helpful mr papooch. I guess my only remaining question then would be like, what other approach could I take to get similar functionality. Becuase I can definitely see the use cases and benefits of having a "guard + decorator - like" functionality that can be used in different modules.

I understand I could make the dependencies required for them global, but would like to avoid that