I haven't been able to get it to work. It seems like the constructor of the auth guard is only called once, but I get a different instance of the service when canActivate is called in the guard.
Is there a way to confirm this? Is there a thing I can log to get the instanceId of the service or something?
Top comments (3)
Does your Auth Guard have any dependencies? In nestjs services become request scoped automatically whenever any of their upstream dependencies are also request scoped.
Guards should be singletons otherwise, if not there might be some additional circumstances I'm unable to guess at unfortunately.
If the constructor is only called once, the guard should be a singleton. What makes youbelieve you're getting a different instance each time?
Sorry for the late reply, I got busy with other things.
The Auth Guard only has 1 dependency, the AuthService. When I try to make the AuthService not static (and a singleton), the AuthService constructor gets called only once, on app startup. Then, I see when I call a method in the AuthService for the Guard, the object that was setup in the constructor is now null, so it's got to be another instance. I don't know why though.
talking about late replies...
I'm hoping you've figured it out by now, but if not I'd be happy to continue chatting about it.
I'm now thinking it could be due to how your AuthService is injected. Is the module you're providing the AuthService, the same module as the guard? And are they provided in a root or global module?