In NestJS, when using a WebSocket Gateway, you can get the full path for the initial connection by accessing the client property of the WebSocket parameter in the handleConnection method. The client property contains information about the WebSocket client, including the request information, such as the URL path.

Here's how you can access the full path for the initial connection in a NestJS WebSocket Gateway:

  1. Create a WebSocket Gateway: First, create a WebSocket Gateway using the @WebSocketGateway() decorator. Define the handleConnection and other WebSocket event handlers as needed.

    typescript
    // websocket.gateway.ts import { WebSocketGateway, OnGatewayConnection } from '@nestjs/websockets'; import { WebSocket } from 'ws'; @WebSocketGateway() export class MyWebSocketGateway implements OnGatewayConnection { handleConnection(client: WebSocket) { // Access the full path for the initial connection const requestUrl = client.upgradeReq.url; console.log('Initial connection URL:', requestUrl); } }
  2. Register the WebSocket Gateway: Next, make sure to register the WebSocket Gateway in the appropriate module of your NestJS application.

    typescript
    // app.module.ts import { Module } from '@nestjs/common'; import { MyWebSocketGateway } from './websocket.gateway'; @Module({ imports: [], controllers: [], providers: [MyWebSocketGateway], }) export class AppModule {}

    Make sure that the MyWebSocketGateway is listed under the providers array in the module.

  3. Access Full Path in Client-side: On the client-side (e.g., JavaScript/TypeScript code running in a web browser or WebSocket client), you can connect to the WebSocket using the WebSocket URL that includes the desired path.

    javascript
    // client.js const socket = new WebSocket('ws://localhost:3000/my-websocket-path');

    In this example, the WebSocket connection is established with the URL 'ws://localhost:3000/my-websocket-path', where 'my-websocket-path' is the desired path for the WebSocket connection.

When a client establishes a WebSocket connection, the handleConnection method in the WebSocket Gateway will be called. You can then access the full path of the initial connection URL using the upgradeReq.url property of the WebSocket client. This allows you to perform specific actions or processing based on the URL path provided by the client during the WebSocket handshake.

Have questions or queries?
Get in Touch