fredtma
fredtma

Reputation: 1053

@nestjs/websockets with Guards fails with host.setType

I am trying to add JWT authentication to nestJs WebSockets.
I am able to connect and send the header from the client-side.
However, I get the error TypeError: host.setType is not a function when I setup nestJs WebSocket with a guard. enter image description here

The Error originates from ws-proxy.js enter image description here

The return value from ExecutionContextHost does not have a property/method called setType but on line 27: it is used

My Guard.ts file is as follow:

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import * as configs from 'config';
import { Socket } from 'socket.io';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from '../jwt-payload.interface';
import { WsException } from '@nestjs/websockets';

@Injectable()
export class JwtGuard implements CanActivate {
  constructor(private readonly jwtService: JwtService) { }

  async canActivate(context: ExecutionContext): Promise<boolean> {

    try {
      const client: Socket = context.switchToWs().getClient<Socket>();
      const authHeader: string = client.handshake.headers.authorization;
      const authToken = authHeader.substring(7, authHeader.length);
      const jwtPayload: JwtPayload = await this.jwtService.verifyAsync(authToken, configs.get('JWT.publicKey'));
      const user: any = this.validateUser(jwtPayload);

      context.switchToWs().getData().user = user;
      return Boolean(user);
    } catch (err) {
      throw new WsException(err.message);
    }
  }

  validateUser(payload: JwtPayload): any {
    return payload;
  }
}

The socket file is

import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';
import { Socket } from 'socket.io';
import { UseGuards} from '@nestjs/common';
import { JwtGuard } from '../../../common/authentication/jwt-guard/jwt.guard';

@UseGuards(JwtGuard)
@WebSocketGateway()
export class ContractGateway {
  @SubscribeMessage('message')
  handleMessage(client: Socket, payload: any): Boolean {
    return true;
  }
}

Has anyone encountered such error and how to resolve it?

Upvotes: 1

Views: 3287

Answers (1)

fredtma
fredtma

Reputation: 1053

Found the issue, package conflict between "@nestjs/websockets": "^6.8.2" & "@nestjs/core": "^6.0.0",. I need to upgrade all @nestjs packages

Upvotes: 0

Related Questions