NestJS Websocket Gateway: using namespaces with the WS adapter

7.3k Views Asked by At

I am working on implementing a Websocket gateway in NestJS 7, as shown in the docs. I use the WS adapter.

const app = await NestFactory.create(ApplicationModule);
app.useWebSocketAdapter(new WsAdapter(app));

The problem I have is that the gateway accepts the connection regardless of the url. So for instance, If I define my gateway like so:

@WebSocketGateway(8080, {namespace: '/v3'}
export class MyGateway {}

Then this gateway's handleConnection is triggered regardless of the path the client requests:

ws://localhost:8080/some-other-path

This unfortunately means that all clients are connecting to every gateway. Is the namespace option only available for the socket.io adapter?

1

There are 1 best solutions below

0
On

You need to specify the path option:

@WebSocketGateway(8080, {path: '/v3'}

Then you can connect with:

const socket = new WebSocket('ws://localhost:8080/v3');

Platform ws doesn't support namespaces. It's a feature of socket.io.

Reference: https://github.com/nestjs/nest/issues/4968#issuecomment-772494179