The Gateway decorator marks a class as a WebSocket gateway. It helps your app talk with clients in real-time using WebSockets.
Gateway decorator in NestJS
@WebSocketGateway(options?)
class YourGateway {
// your methods here
}@WebSocketGateway()
class ChatGateway {}@WebSocketGateway({ namespace: '/chat' })
class ChatGateway {}@WebSocketGateway({ port: 3001 })
class NotificationGateway {}This gateway listens on the '/chat' namespace. When a client sends a 'message' event, the server logs it and replies with a confirmation message.
import { WebSocketGateway, SubscribeMessage, MessageBody, ConnectedSocket } from '@nestjs/websockets'; import { Socket } from 'socket.io'; @WebSocketGateway({ namespace: '/chat' }) export class ChatGateway { @SubscribeMessage('message') handleMessage(@MessageBody() message: string, @ConnectedSocket() client: Socket): string { console.log(`Received message: ${message}`); return `Server says: ${message}`; } }
Use the Gateway decorator only on classes meant to handle WebSocket events.
Namespaces help organize different WebSocket channels in your app.
Remember to import necessary decorators and types from '@nestjs/websockets'.
The Gateway decorator turns a class into a WebSocket gateway.
It enables real-time communication between server and clients.
You can customize it with options like namespace and port.
Practice
What is the main purpose of the @WebSocketGateway() decorator in NestJS?
Solution
Step 1: Understand the role of @WebSocketGateway()
This decorator marks a class as a WebSocket gateway, enabling real-time communication between server and clients.Step 2: Compare with other options
Options B, C, and D relate to REST controllers, database entities, and middleware, which are unrelated to WebSocket gateways.Final Answer:
To turn a class into a WebSocket gateway for real-time communication -> Option AQuick Check:
@WebSocketGateway() creates WebSocket gateways [OK]
- Confusing WebSocketGateway with REST controllers
- Thinking it creates database entities
- Assuming it handles HTTP middleware
Which of the following is the correct syntax to create a WebSocket gateway with a custom namespace /chat?
?Solution
Step 1: Recall the correct options object syntax
The@WebSocketGateway()decorator accepts an options object wherenamespaceis a valid key to set the namespace.Step 2: Evaluate each option
@WebSocketGateway({ namespace: '/chat' }) export class ChatGateway {} correctly uses{ namespace: '/chat' }. @WebSocketGateway('/chat') export class ChatGateway {} incorrectly passes a string directly. @WebSocketGateway(namespace: '/chat') export class ChatGateway {} uses invalid syntax. @WebSocketGateway({ path: '/chat' }) export class ChatGateway {} usespathwhich is not the correct key for namespace.Final Answer:
@WebSocketGateway({ namespace: '/chat' }) export class ChatGateway {} -> Option CQuick Check:
Use options object with namespace key [OK]
- Passing namespace as a direct string argument
- Using invalid syntax inside decorator
- Confusing 'path' with 'namespace'
Given the following code, what will be the output when a client connects?
@WebSocketGateway()
export class MyGateway {
handleConnection(client: any) {
console.log('Client connected');
}
}Solution
Step 1: Understand handleConnection behavior
In NestJS WebSocket gateways,handleConnectionis a lifecycle method called automatically when a client connects.Step 2: Analyze the code output
The method logs 'Client connected' to the console, so this message appears on each client connection.Final Answer:
The message 'Client connected' is logged to the console when a client connects -> Option DQuick Check:
handleConnection logs message on client connect [OK]
- Thinking handleConnection needs a decorator
- Assuming no output without explicit event listener
- Believing server crashes without manual init
Identify the error in this WebSocket gateway code:
@WebSocketGateway()
export class AppGateway {
@SubscribeMessage('message')
handleMessage(client, payload) {
client.emit('message', payload);
}
}Solution
Step 1: Understand @SubscribeMessage handler behavior
In NestJS, message handlers should return the response payload, not emit directly on the client.Step 2: Analyze the code's client.emit usage
Callingclient.emitis incorrect; the framework handles sending the return value automatically.Final Answer:
The method handleMessage should return the payload instead of emitting -> Option BQuick Check:
Return payload in handler, don't emit manually [OK]
- Calling client.emit instead of returning data
- Thinking @SubscribeMessage needs parentheses
- Assuming handler must be async always
You want to create a WebSocket gateway that listens on port 8081 and uses the namespace /notifications. Which of the following is the correct way to define this gateway?
Solution
Step 1: Recall the correct options object usage
The@WebSocketGateway()decorator accepts a single options object where you can specify bothportandnamespace.Step 2: Evaluate each option
@WebSocketGateway({ port: 8081, namespace: '/notifications' }) export class NotificationGateway {} correctly passes an object with bothportandnamespace. @WebSocketGateway(8081, { namespace: '/notifications' }) export class NotificationGateway {} incorrectly uses positional arguments mixing number and object. @WebSocketGateway({ port: 8081 }) @WebSocketGateway({ namespace: '/notifications' }) export class NotificationGateway {} uses two decorators which is invalid. @WebSocketGateway('/notifications', 8081) export class NotificationGateway {} uses positional arguments in wrong order and types.Final Answer:
@WebSocketGateway({ port: 8081, namespace: '/notifications' }) export class NotificationGateway {} -> Option AQuick Check:
Use single options object for port and namespace [OK]
- Passing port and namespace as separate arguments
- Using multiple @WebSocketGateway decorators
- Mixing argument types and order incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
