Learn NestJS Β· 12/14

Real-time Communication

7 min read

Real-time Communication with NestJS πŸš€

Hey there, future real-time guru! Ever wondered how applications like chat, live notifications, or collaborative editing tools work their magic? The secret ingredient is real-time communication.

The Problem: Traditional web applications follow a request-response model. The client asks for something, and the server responds. This is perfectly fine for many things, but what if the server has an update for the client? The client would have to constantly ask, "Anything new? Anything new?" which is wildly inefficient. Imagine a postman having to visit your house every second to check for new mail. Exhausting, right?

The Solution: WebSockets! WebSocket is a protocol that allows for a two-way interactive communication session between a user's browser and a server. This means the server can "push" information to the client the moment it's available, without the client having to ask. It's like having a dedicated, open phone line between the two.

In this guide, we'll explore how to harness the power of WebSockets in your NestJS applications. So, grab your favorite beverage, and let's get this real-time party started! β˜•


1. WebSockets in NestJS: The Gateway Pattern πŸšͺ

In NestJS, the central piece of the WebSocket puzzle is the Gateway. Think of a gateway as a controller, but specifically for WebSocket communication. It's the entry and exit point for all your real-time events.

Getting Started: Installation

First things first, let's get the necessary packages installed. NestJS provides excellent support for WebSockets out-of-the-box with the @nestjs/websockets and @nestjs/platform-socket.io packages.

bash
npm i --save @nestjs/websockets @nestjs/platform-socket.io

Creating Your First Gateway

With the dependencies in place, we can create our first gateway. The Nest CLI makes this a breeze:

bash
nest generate gateway events

This command will create an events.gateway.ts file. Let's take a look at a basic gateway implementation.

typescript
// events.gateway.ts
import {
  WebSocketGateway,
  SubscribeMessage,
  MessageBody,
  WebSocketServer,
  ConnectedSocket,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway()
export class EventsGateway {
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('events')
  handleEvent(
    @MessageBody() data: string,
    @ConnectedSocket() client: Socket,
  ): string {
    return data;
  }
}

Let's break this down:

  • @WebSocketGateway(): This decorator marks the class as a gateway. You can pass options to it, like the port or namespace.
  • @WebSocketServer(): This decorator gives you access to the underlying Socket.IO server instance, allowing you to emit events to all connected clients.
  • @SubscribeMessage('events'): This decorator binds the handleEvent method to listen for incoming messages on the 'events' channel.
  • @MessageBody(): This decorator extracts the payload from the incoming message.
  • @ConnectedSocket(): This decorator provides access to the client socket instance.

Finally, don't forget to add your new gateway to the providers array in your module file (e.g., app.module.ts).


2. Emitting and Listening to Real-time Events πŸ”ŠπŸ‘‚

Now that we have our gateway set up, let's make it do something interesting! Real-time communication is all about emitting events from one end and listening for them on the other.

From Client to Server

Imagine you have a client application (like a browser) and you want to send a message to your NestJS server. You would use a client-side library like socket.io-client.

javascript
// client-side code
import { io } from "socket.io-client";

const socket = io("http://localhost:3000"); // Connect to your NestJS server

socket.emit('events', 'Hello from the client!');

socket.on('events', (data) => {
  console.log('Received a message from the server:', data);
});

In this example, the client emits a message on the 'events' channel with the payload 'Hello from the client!'. Our handleEvent method in the EventsGateway will receive this message.

From Server to Client

The handleEvent method in our gateway currently just returns the data it receives. This sends a direct reply to the client that sent the message. But what if we want to proactively send messages to the client?

typescript
// events.gateway.ts
// ... (imports)

@WebSocketGateway()
export class EventsGateway {
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('events')
  handleEvent(
    @MessageBody() data: string,
    @ConnectedSocket() client: Socket,
  ): void {
    client.emit('events', `You sent: ${data}`); // Send a message back to the sender
  }
}

Here, we're using client.emit() to send a message specifically back to the client that initiated the event.

Fun Fact: The term "WebSocket" was coined by Ian Hickson and Michael Carter and was standardized by the IETF as RFC 6455 in 2011.


3. Integrating Authentication within WebSockets πŸ”

In the wild west of the internet, you can't just let anyone connect to your real-time endpoints. Authentication is crucial.

The most common approach is to verify authentication during the initial WebSocket handshake. When a client tries to connect, you can check for a valid authentication token (like a JWT) in the connection headers.

A common way to implement this is by using a NestJS Guard.

typescript
// ws-auth.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Socket } from 'socket.io';

@Injectable()
export class WsAuthGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const client: Socket = context.switchToWs().getClient<Socket>();
    const authorizationHeader = client.handshake.headers.authorization;
    // Your authentication logic here
    // e.g., verify a JWT token
    const isValid = this.validateToken(authorizationHeader);
    return isValid;
  }

  private validateToken(authHeader: string): boolean {
    // Implement your token validation logic
    return true; // for demonstration
  }
}

Then, you can apply this guard to your gateway or specific message handlers.

typescript
// events.gateway.ts
import { UseGuards } from '@nestjs/common';
import { WsAuthGuard } from './ws-auth.guard';
// ...

@UseGuards(WsAuthGuard)
@WebSocketGateway()
export class EventsGateway {
  // ...
}

Now, only authenticated clients will be able to connect and interact with your gateway.

A word of caution: JWTs can expire. Since WebSocket connections can be long-lived, a token that was valid at the start might expire during the connection. You'll need to handle this by either re-authenticating or gracefully disconnecting the client.


4. Broadcasting Messages to Multiple Clients πŸ“’

What's the fun in real-time if you can't share the excitement with everyone? Broadcasting allows you to send a message to all connected clients, or a specific group of them.

Broadcasting to All

To send a message to every single client connected to your gateway, you can use the server instance we injected with @WebSocketServer().

typescript
// events.gateway.ts
// ...

@WebSocketGateway()
export class EventsGateway {
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('chatToServer')
  handleMessage(@MessageBody() message: string): void {
    this.server.emit('chatToClient', message);
  }
}

In this example, when any client sends a message on the chatToServer channel, the server will broadcast that message to all connected clients on the chatToClient channel.

Broadcasting to a "Room"

Sometimes you don't want to shout to the entire world. For more targeted communication, you can use "rooms". A room is a logical grouping of sockets.

Imagine a chat application with different channels. You'd want messages in the #general channel to only go to users in that channel.

typescript
// events.gateway.ts
// ...

@WebSocketGateway()
export class EventsGateway {
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('joinRoom')
  handleJoinRoom(
    @MessageBody() room: string,
    @ConnectedSocket() client: Socket
  ) {
    client.join(room);
    client.emit('joinedRoom', `You have joined the ${room} room.`);
  }

  @SubscribeMessage('messageToRoom')
  handleMessageToRoom(
    @MessageBody() payload: { room: string; message: string }
  ): void {
    this.server.to(payload.room).emit('roomMessage', payload.message);
  }
}

Here, a client can join a room by sending a joinRoom event. Then, when a messageToRoom event is received, the server broadcasts the message only to the clients within that specific room using this.server.to(payload.room).

Real-world Scenario: Think of a live auction application. When a new bid is placed on an item, you only want to notify the users who are currently viewing that specific item's auction page. Rooms are perfect for this! Each item auction could be its own room.

And that's a wrap on our whirlwind tour of real-time communication in NestJS! You're now equipped with the fundamental knowledge to build your own interactive and dynamic applications. Happy coding! πŸ’»


Extra Reading & References πŸ“š

Challenge

Your task is to implement a NestJS WebSocket gateway for a real-time chat application. This gateway will manage chat rooms and broadcast messages to specific rooms.

Requirements:

  1. Create a ChatGateway class.
  2. Configure the gateway to listen on port 8080.
  3. Inject the Server instance from socket.io into the gateway.
  4. Implement a message handler for a joinRoom event. This handler must:
    • Extract the room name from the message payload.
    • Use the client's socket to join the specified room.
    • Emit a joinedRoom event back only to the client that just joined, sending the room name as the payload.
  5. Implement a message handler for a sendMessage event. This handler must:
    • Extract an object containing room and message from the payload.
    • Broadcast the message to all clients within the specified room using a newMessage event.

Expected result

Your code should be a complete NestJS Gateway class named ChatGateway.

The solution must include:

  • A @WebSocketGateway(8080) decorator on the class.
  • A class property decorated with @WebSocketServer() to hold the Server instance.
  • A method decorated with @SubscribeMessage('joinRoom') that correctly handles the logic for a client joining a room and receiving a confirmation. The method signature should use @MessageBody() and @ConnectedSocket() to access the payload and client socket respectively.
  • A method decorated with @SubscribeMessage('sendMessage') that correctly broadcasts a message to all clients in a specific room. The method signature should use @MessageBody() to access the payload containing both the room and the message.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.