Recently, while working on my app with NestJS, I came across an issue related to the use of guards using @UseGuards()
. In order to protect my controller, I created two guards as follows:
JwtAuthGuard:
import { AuthGuard } from '@nestjs/passport';
export class JwtAuthGuard extends AuthGuard('jwt') {}
ApiKeyGuard:
@Injectable()
export class ApiKeyGuard implements CanActivate {
constructor(private configService: ConfigService) {}
canActivate (context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
const { apikey } = request.headers;
if (apikey === env.get('API_KEY')) return true;
else throw new UnauthorizedException();
}
}
This is how my Controller is set up:
@Get('/:users')
@UseGuards(ApiKeyGuard)
getUser(): {
return this.userService.getUser();
}
The services associated with the Controller are defined like this:
@Injectable()
export class UserService {
constructor(private dummyService:DummyService) {}
getUser() {
return this.dummyService.getUser();
}
Additionally, here is the content of the module.ts
file:
@Module({
imports: [...],
controllers: [userController],
providers: [....],
exports: [UserService],
})
export class CouponModule {}
I also have another module named CouponModule
which includes a CouponController
utilizing @UseGuard()
, along with its respective services. The CouponService
shows circular dependencies with the UserService
and also relies on the DummyService
.
Challenge:
Upon implementing the @UseGuards(ApiKeyGuard)
in the controller, I began encountering errors whenever the app processed requests:
TypeError: Cannot read property 'getUser' of undefined
Strangely enough, when switching to @UseGuards(JwtAuthGuard)
, the app worked fine without any errors. Even after removing the @UseGuards()
decorator, the error persisted.
In an attempt to resolve this issue, I added the DummyServices
to the providers section of both modules' module.ts
files, but unfortunately, the problem remained unsolved.
Despite conducting extensive research and investigation, I have yet to identify the root cause or find a suitable solution for this dilemma.