Search code examples
authenticationjwtnestjs

JWT Guard returning "Converting circular structure to JSON"


i have this nest code to verify the bearer token of a user after they login in but it gives me the error:

ERROR [ExceptionsHandler] Converting circular structure to JSON
--> starting at object with constructor 'Socket'
|     property 'parser' -> object with constructor 'HTTPParser'
--- property 'socket' closes the circle

this is my login code and my attempt to authorize the user: user.module:

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    TypeOrmModule.forFeature([User, Level]),
    JwtModule.register({
      secret: 'abc123',
      signOptions: { expiresIn: '60d' },
    }),
  ],
  controllers: [UserController],
  providers: [UserService, JwtStrategy],
})
export class UserModule {}

user.controller:

import { jwtAuthGuard } from 'src/guards/jwt.guard';
 @Get("")
    @UseGuards(jwtAuthGuard)
    getUser(@Req() req: Request) {
        return this.UserService.getUser(req)
    }

jwt.guard:

import { ExecutionContext, Injectable } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
import { Observable } from "rxjs";

@Injectable()
export class jwtAuthGuard extends AuthGuard('jwt'){
    canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {        
        return super.canActivate(context)
    }

}

jwt.strategy:

export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private userService: UserService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: 'abc123', // Access the environment variable
    });
  }

  validate(payload: any) {
    return payload;
  }
}

this is my entire code i omitted some of the imports and some code in the controller and module in other not to make this post too long


Solution

  • the solution is in the user.conroller, i was passing the entire req inside the getUser(req) method, this is how the code should have been written:

     @Get("")
        @UseGuards(jwtAuthGuard)
        getUser(@Req() req: Request) {
            return this.UserService.getUser(req.body)
        }
    

    so from this:getUser(req) to getUser(req.body)