Because of this issue https://github.com/nestjs/nest/issues/882#issuecomment-1046242517
the guard doesnt work on handleConnection. The comments have some examples and there is one that worked for me:
export type SocketMiddleware = (socket: Socket, next: (err?: Error) => void) => void;
export const WSAuthMiddleware = (jwtService: JwtService, configService: ConfigService, knex: Knex, logger: Logger): SocketMiddleware => {
return async (socket, next) => {
try {
const token = socket?.handshake?.auth?.token;
if (!token) {
throw 'Missing token';
}
const decodedToken = await validateToken(token, jwtService, configService);
next();
} catch (error) {
logger.error(`${error}`);
next({
name: 'unauthorized',
message: `${error}`,
});
}
};
};
async function validateToken(token: string, jwtService: JwtService, configService: ConfigService): Promise<IToken> {
const jwtSecret = configService.get('jwtSecret');
const decodedToken = await jwtService.verifyAsync(token, { secret: jwtSecret });
if (!decodedToken) {
throw 'Invalid token';
}
return decodedToken;
}
events.gateway.ts
async afterInit() {
const middle = WSAuthMiddleware(this.jwtService, this.configService, this.knex, this.logger);
this.io.use(middle);
this.logger.log('Initialized');
}
When I pass token null or bad format jwt, the client is not receiving the error, it only receives if i kill the server.
I logged the socket.disconnected, which is true all time.
In nestjs, how do I make it work to client side to receive error event lifecyle?