skip to Main Content

I have a NestJS application with a JwtAuthGuard that I’m trying to use to protect an endpoint. The JwtAuthGuard is responsible for authenticating and authorizing requests based on JWT tokens.

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { AuthService } from 'src/auth/auth.service';

@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(private readonly authService: AuthService) {}

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return true;
  }
}

I tried to use it on this endpoint

  @Get('/user-data')
  @UseGuards(JwtAuthGuard)
  userData(@Req() req: Request) {
    const jwt = req.cookies['jwt'];
    return { jwt };
  }

but it throws this error

ERROR [ExceptionHandler] Nest can't resolve dependencies of the JwtAuthGuard (?). Please make sure that the argument dependency at index [0] is available in the AuthModule context.

Potential solutions:
- Is AuthModule a valid NestJS module?
- If dependency is a provider, is it part of the current AuthModule?
- If dependency is exported from a separate @Module, is that module imported within AuthModule?
  @Module({
    imports: [ /* the Module containing dependency */ ]
  })

This error suggests that there’s an issue with the dependency injection in the JwtAuthGuard constructor. Specifically, it’s unable to resolve the AuthService dependency.
even though I exported the AuthService
and refreshed everything

Auth Module:

import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { PrismaModule } from 'src/prisma/prisma.module';
import { AuthController } from './auth.controller';
import { GoogleStrategy } from './google.strategy';
import { PassportModule } from '@nestjs/passport';
import { JwtService } from '@nestjs/jwt';

@Module({
  controllers: [AuthController],
  providers: [AuthService, GoogleStrategy, JwtService],
  imports: [
    PrismaModule,
    PassportModule.register({ defaultStrategy: 'google' }),
  ],
  exports: [AuthService],
})
export class AuthModule {}

App Module:

import { Module, ValidationPipe } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AuthModule } from './auth/auth.module';
import { APP_PIPE } from '@nestjs/core';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { AuthService } from './auth/auth.service';
import { PrismaService } from './prisma/prisma.service';

@Module({
  imports: [
    ConfigModule.forRoot(),
    AuthModule,
    JwtModule.register({
      secret: process.env.TOKEN,
      signOptions: { expiresIn: '30d' },
    }),
  ],
  providers: [
    AuthService,
    PrismaService,
    JwtService,
    {
      provide: APP_PIPE,
      useClass: ValidationPipe,
    },
  ],
})
export class AppModule {}

What is the problem

the problem is here

constructor(private readonly authService: AuthService) {}

if I remove this line it will work!

The problem seems to revolve around the AuthService not being injected correctly into the JwtAuthGuard. If I remove the constructor line constructor(private readonly authService: AuthService) {}, the error goes away, but this is not a solution to the problem.

I hope this additional information helps provide a clearer picture of the issue I’m facing with my NestJS application. If you have any suggestions or solutions, please feel free to share.

2

Answers


  1. Add JwtAuthGuard as provider in AuthModule.

    Login or Signup to reply.
  2. Remove JwtService from the provider array and add JwtStratagy (create one if you have not)

    Adding JwtService to the provider will cause a circular dependency error

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search