I am facing an issue where I'm receiving duplicate WebSocket requests when using Socket.io with a NestJS WebSocketGateway. Here's my setup:
[enter image description here](https://i.sstatic.net/h7eWK.png)
import {
ConnectedSocket,
MessageBody,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { OnModuleInit } from '@nestjs/common';
import { CreativeService } from '../modules/creative/creative.service';
import { CreateMessageDto } from './dto/chat.dto';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../modules/users/users.service';
@WebSocketGateway({
cors: {
origin: '*',
},
})
export class ChatGateway implements OnModuleInit {
constructor(
private readonly creativeService: CreativeService,
private readonly jwtService: JwtService,
private readonly userService: UsersService,
) {}
@WebSocketServer()
server: Server;
onModuleInit(): any {
this.server.on('connection', async (socket: Socket) => {
console.log('socket', socket.id);
try {
const token = socket.handshake.headers.authorization;
const splitToken = token.split(' ')[1];
const decodedToken = this.jwtService.verify(splitToken);
const requestUser = await this.userService.findOne(decodedToken.id);
console.log('I am getting Called from OnModuleInit');
if (!requestUser) {
throw new Error('User not found');
}
// Attach the user to the socket object
socket['user'] = requestUser;
// console.log('user', requestUser);
} catch (error) {
// Send an error message to the client
socket.emit('error', { message: error.message });
// You can also consider disconnecting the socket
socket.disconnect();
}
});
}
@SubscribeMessage('newChatMessage')
onNewMessage(
@MessageBody() body: CreateMessageDto,
@ConnectedSocket() socket: Socket,
) {
const user = socket['user'];
if (!user) {
throw new Error('User not found');
}
console.log('Received message', body, 'From', user.email);
console.log('I am getting Called from SubscribeMessage');
this.server.emit('newChatMessage', {
videoId: body.videoId,
sender: user.email,
message: body.message,
});
}
}
I have attempted to debug the React client, but I'm encountering the same issue in Postman. Both clients are consistently sending two WebSocket requests simultaneously. Can someone help me identify and resolve the root cause of this issue?
The ChatGateway
was added to multiple providers
arrays which caused Nest to instantiate the gateway more than once. Each instance was receiving the message, hence processing it twice. Keeping the gateway in a single providers
array will fix the probelm