Search code examples
websocketnestjs

I can not connect to a WebSocket build on NestJS WebSocket Gateway


The light WebSocket example has been implemented according to the NestJS documentation and an example on github

According to the logs I see that the gateway has been loaded, registered, and subscribed.

[Nest] 113767  - 10/31/2023, 9:43:49 PM     LOG [WebSocketsController] MigrationGateway subscribed to the "message" message

The application is running on port 3000

[Nest] 113767  - 10/31/2023, 9:43:49 PM     LOG [NestApplication] Nest application successfully started
Application is running on: http://[::1]:3000

The gateway is registered by the decorator without extra options

@WebSocketGateway()
export class MigrationGateway implements OnGatewayConnection, OnGatewayDisconnect {

I connect to the socket from the console and receive.

const socket = new WebSocket('ws://localhost:3000');
WebSocket connection to 'ws://localhost:3000/' failed: 

I also tried from bash.

wscat -c ws://localhost:3000
error: socket hang up

I do not see any issue in the server log. It is like it needs to be set up.

I have not checked the socket.io client.

import io from 'socket.io-client';
const socket = io('http://localhost:3000');

But I do not think this is a problem.

Suggest to me where to look into the issue.

Regards.


Solution

  • If you're looking to use ws with NestJS you need to make use of the WsAdapter from @nestjs/platform-ws. By default, and just following the docs, Nest uses the SocketIoAdapter from @nestjs/platform-socket.io which needs to be connected to using the socket.io-client package at http://localhost:3000 instead of ws://localhost:3000