Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 42 ยท Projects

Project: Realtime Chat Gateway

Build a realtime chat gateway in NestJS: authenticate on connect, join rooms, validate every message, keep room history, and watch it all run in a loopback demo.

In this project you design a realtime chat gateway: clients connect over a WebSocket, prove who they are, join rooms, send messages that everyone in the room receives, and ask for recent history. It pulls together most of what you learned in WebSockets and Gateways, guards, pipes and validation and exception filters.

A chat service is a good project because every message crosses a trust boundary. Anybody can open a socket and send any bytes, so the gateway has to check identity once at connect time and check the shape of every single message after that.

The real NestJS code below is read-only, because it needs Node, npm and a WebSocket library. The runnable parts are stand-ins: a tiny hand-written WebSocket server on 127.0.0.1 that runs the same design (connect check, rooms, validation, history), and a browser-console demo of the validator and the history buffer. They show the logic, not Nest itself.

What the gateway must do

Auth on connect Unknown tokens are refused at once.
Rooms Join, leave, and talk to one room only.
Validation Every message is checked before use.
History New members can read the last few messages.
1 / 2

The message protocol

Decide the wire format before writing any code. Every frame is one JSON object with an event name, which is exactly what Nest's @SubscribeMessage() routes on:

Client sends Meaning Server answers
{event: "join", room} Enter a room joined to the sender, presence to the others
{event: "leave", room} Leave a room left to the sender, presence to the others
{event: "message", room, text} Say something message to everyone in the room
{event: "history", room} Ask for recent messages history to the sender

Failures always come back as {event: "error", reason} to the sender only, never to the room. A client that sends a bad frame must not be able to disturb anyone else.

sequenceDiagram
  participant A as Alice
  participant G as Gateway
  participant B as Bob
  A->>G: connect with token
  G-->>A: welcome
  A->>G: join general
  B->>G: join general
  G-->>A: presence bob joined
  A->>G: message hello
  G-->>A: message hello
  G-->>B: message hello

Alice and Bob share the room; the gateway fans each message out to every member, including the sender.

Authentication on connect

A browser WebSocket cannot set custom headers, so the token usually travels in the URL query string or in the Socket.IO auth object. In a Nest gateway you check it in handleConnection and disconnect strangers immediately:

TypeScript
@WebSocketGateway({ cors: { origin: ['https://chat.example.com'] } })
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer() server: Server;

  constructor(
    private readonly auth: AuthService,
    private readonly rooms: RoomsService,
  ) {}

  async handleConnection(client: Socket) {
    const token = client.handshake.auth?.token;
    const user = await this.auth.verify(token).catch(() => null);
    if (!user) {
      client.emit('error', { reason: 'unauthorized' });
      client.disconnect(true);
      return;
    }
    client.data.user = user;
    client.emit('welcome', { user: user.name });
  }

  handleDisconnect(client: Socket) {
    this.rooms.leaveAll(client.id);
  }
}

Two details matter. First, the identity is stored once on the connection (client.data.user) and every later handler reads it from there, so a client can never claim to be someone else in a message body. Second, handleDisconnect cleans up, otherwise the room membership map leaks sockets that no longer exist.

Token handling itself (signing, expiry, refresh) is the topic of Authentication with JWT; the gateway only calls verify.

Handlers, validation and rooms

Each message type becomes a @SubscribeMessage() method. A DTO plus ValidationPipe rejects malformed payloads before your code sees them:

TypeScript
export class SendMessageDto {
  @IsString() @Matches(/^[a-z0-9-]{1,20}$/)
  room: string;

  @IsString() @Length(1, 200)
  text: string;
}

@UsePipes(new ValidationPipe({
  whitelist: true,
  exceptionFactory: (errors) => new WsException(errors),
}))
@SubscribeMessage('message')
async onMessage(
  @ConnectedSocket() client: Socket,
  @MessageBody() dto: SendMessageDto,
) {
  if (!client.rooms.has(dto.room)) {
    throw new WsException('join the room first');
  }
  const saved = this.rooms.remember(dto.room, client.data.user.name, dto.text);
  this.server.to(dto.room).emit('message', saved);
}

exceptionFactory matters: the default ValidationPipe throws an HTTP exception, which a WebSocket handler does not translate into an error event. Throwing WsException does. Membership is checked on the server (client.rooms) because the client's room value is only a claim.

Joining uses the socket library's room support. With Socket.IO that is client.join(room) and this.server.to(room).emit(...). The plain ws adapter has no rooms, so you would keep your own Map of room names to sockets, which is exactly what the stand-in below does.

Room history

Keep history in a small service so the gateway stays thin and the buffer can be unit tested alone:

TypeScript
@Injectable()
export class RoomsService {
  private readonly history = new Map<string, ChatMessage[]>();
  private nextId = 1;

  remember(room: string, user: string, text: string): ChatMessage {
    const list = this.history.get(room) ?? [];
    const message = { id: this.nextId++, room, user, text };
    list.push(message);
    if (list.length > 50) list.shift(); // bounded memory
    this.history.set(room, list);
    return message;
  }

  recent(room: string): ChatMessage[] {
    return this.history.get(room) ?? [];
  }
}

In memory is fine for a lesson and for one process. A real deployment usually writes messages to a database (see Connecting to a Database) and serves history from there, so restarts do not erase conversations.

Stand-in: a loopback chat gateway on real WebSocket frames

This demo is not Nest and not the ws package. It is a minimal WebSocket server written for this lesson: it does the HTTP upgrade handshake, reads masked client frames, and writes unmasked server frames (text frames under 64 KB only, no fragmentation, no ping handling). The client is Node's built-in WebSocket. The ChatGateway class inside follows the design above: token check on connect, join, leave, message, history, validation, and per-room history.

Node.js A chat gateway on a loopback WebSocket

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output per client. Mallory's token is unknown, so the gateway closes the connection with code 4401 (codes from 4000 to 4999 are free for applications) and sends nothing else. Bob's empty message, Alice's 60-character message and Bob's message to a room he never joined each produced an error event for that sender only. Carol joined late, so she got history with the single valid message, and when Bob disconnected the gateway told the remaining members he had left. (Bob's own close code 1005 only means he closed without sending a status code.)

Stand-in: the validator and the history buffer on their own

The two small pieces that carry the most risk are the validator and the bounded history. They are plain functions, so you can test them without any network, which is also how you would unit test the matching Nest services. This one runs in the browser console editor.

JS Validator and bounded history, tested alone

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The history keeps only the newest three entries, yet ids keep counting up, so a client can tell it missed messages. A validator that returns all problems at once (instead of stopping at the first) gives clients a better error report, which is also how class-validator behaves.

Hardening checklist

Before you call a gateway finished, walk through these questions:

  • Origin: does the gateway restrict CORS origins, so a random website cannot open sockets for a logged-in user?
  • Size limits: is there a maximum payload size on the adapter, so one client cannot send megabytes per frame?
  • Rate: can a client send a thousand messages a second? Throttle per connection (see Caching, Throttling and Scheduling).
  • Token expiry: what happens when the token expires while the socket stays open? Many apps re-check on every message or force a reconnect.
  • Scaling: with two server instances, a room's members are split between them. Socket.IO needs an adapter (for example Redis) so to(room).emit reaches all of them.
  • Testing: can you open two test clients against app.listen(0) and assert on the messages they receive? See Testing Nest Applications.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where should the gateway verify the user's identity, and why?

    Identity is established once when the socket opens and kept on the connection. A user field inside a message is just a claim any client could fake.
  2. 2. A client sends {event: 'message', room: 'general', text: ''}. Who should receive the error?

    A bad frame is the sender's problem. Broadcasting errors would let one client disturb the whole room.
  3. 3. Why must the server check room membership before accepting a message?

    Without a server-side check, any client could post into rooms it never joined.
  4. 4. Why does the real ValidationPipe need an exceptionFactory that returns a WsException inside a gateway?

    Pipes work on gateways, but the exception type must be one that the WebSocket exception layer understands.
  5. 5. What problem appears when you run two instances of an in-memory chat gateway behind a load balancer?

    Rooms and history live in each process's memory, so you need a shared adapter or store to fan messages out across instances.

Summary

  • A chat gateway has four jobs: authenticate on connect, manage rooms, validate every message, and serve bounded history.
  • Store the verified identity on the connection and never trust a user name or room in a message body.
  • Errors go back only to the sender; presence and messages go to the room.
  • In a real Nest gateway use handleConnection, @SubscribeMessage(), DTOs with ValidationPipe and a WsException factory, and keep rooms and history in a service.
  • In-memory state works for one process; scaling out needs an adapter and a database.

Next, test yourself with Exercises: Core Concepts.