typescriptnestjsauth-guard

context.switchToHttp is not a function


This is my combined Auth Guard in this I am getting the error "context.switchToHttp is not a function."

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { JwtAuthGuard } from './jwt.strategy';
import { KakaoAuthGuard } from './kakao.strategy';
import { GoogleAuthGuard } from './oauth.strategy';

@Injectable()
export class CombinedAuthGuard implements CanActivate {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    try {
      
    const jwtAuthGuard = new JwtAuthGuard();
    const googleAuthGuard = new GoogleAuthGuard();
    const kakaoAuthGuard = new KakaoAuthGuard();

    const request = context.switchToHttp().getRequest();
    const jwtAuthCanActivate = await jwtAuthGuard.canActivate(request);
    const googleAuthCanActivate = await googleAuthGuard.canActivate(
      request,
    );
    const kakaoAuthCanActivate = await kakaoAuthGuard.canActivate(request);

    return (
      !!googleAuthCanActivate || !!jwtAuthCanActivate || !!kakaoAuthCanActivate
    );

  } catch (error) {
      console.log(error);
  }
  }
}

I have tried to get context type and then apply checks on the basis of it. But I was not able to get request. Basically I want to get request from the context.


Solution

  • You're passing request to the jwtAtuhGuard.canActivate(), the googleAuthGuard.canActivate(), and the kakaoAuthGuard.canActivate(). Instead, you should pass context. Assuming that these are both guards that implements CanActivate, you're passing in the wrong value.