DEV Community

Cover image for How to build a real-time chat backend in Node.js with NestJS: Socket.IO and PostgreSQL
Kamil Mysliwiec for NestJS

Posted on

How to build a real-time chat backend in Node.js with NestJS: Socket.IO and PostgreSQL

A chat backend is the classic WebSocket demo: open a socket, broadcast whatever comes in, done in fifty lines. Then you start asking what happens at the edges. Someone leaves a room but still has a tab open on it. A message gets broadcast, and the process restarts before it's saved. An access token expires while the socket it opened stays connected for three days. One client sends a thousand messages a second.

Those edges are what this article is about. We'll build a chat backend in Node.js with NestJS 12, Socket.IO and PostgreSQL: rooms with members, messages that arrive live and are stored before anyone sees them, a history clients page through over REST, presence and typing indicators, and a rate limit per user. Every file is here, along with the commands, the migration, the end-to-end tests and a production checklist. The same app is also a tutorial in the NestJS docs: Build a real-time chat backend in Node.js.

What the chat backend does

When we're done, the API will:

  • Accept Socket.IO connections signed in with the same access tokens as the REST routes, and close each connection when its token expires.
  • Store every message in PostgreSQL before broadcasting it, and check that the sender belongs to the room in the very statement that stores it, for every message.
  • Validate everything a client sends over the socket with a Zod schema, and answer each refusal with a status code the client can act on.
  • Serve a room's history over REST, one page at a time, with keyset pagination.
  • Show who has a room open, and who is typing.
  • Limit how fast each user can send messages.
  • Prove all of that with end-to-end tests that use real Socket.IO clients against a listening server.

Here are the endpoints and events, and where each one comes from:

Endpoint or event Section
POST /auth/sign-up, POST /auth/token, POST /auth/token/refresh, POST /auth/token/revoke, GET /me, GET /health/live, GET /health/ready Starting point: the JWT API
POST /rooms, GET /rooms, POST /rooms/:id/members, DELETE /rooms/:id/members/me, GET /rooms/:id/messages Rooms and history over REST
join, leave, message and typing from clients; message, presence, typing and exception from the server The Socket.IO gateway

Starting point: the JWT API

Sign-up, access and refresh tokens, Zod validation, Drizzle and PostgreSQL all come from the API in Build a REST API with JWT authentication. I won't explain those parts again here; this article starts where that one ends.

Create the project and install everything we'll use. That's the JWT API's packages, plus @nestjs/websockets with its Socket.IO platform, and socket.io-client for the tests:

$ npm i -g @nestjs/cli
$ nest new chat-api --minimal
$ cd chat-api
$ npm uninstall @nestjs/platform-express @types/express
$ npm i --save @nestjs/platform-node zod @nestjs/config @nestjs/drizzle drizzle-orm@rc pg @nestjs/authentication @nestjs/throttler @nestjs/swagger @nestjs/terminus @nestjs/websockets @nestjs/platform-socket.io socket.io
$ npm i --save-dev drizzle-kit@rc @types/pg @nestjs/testing vitest vite @electric-sql/pglite socket.io-client
Enter fullscreen mode Exit fullscreen mode

From the finished JWT API, copy these files unchanged:

  • everything under src/auth/, src/users/ and src/health/: the sign-in controller and its schemas, the credentials service, the Drizzle refresh-token store, the users repository, GET /me and the health checks
  • src/config.ts, src/main.ts, drizzle.config.ts and vitest.config.e2e.ts
  • test/refresh-token.store.e2e-spec.ts

Leave out src/notes/ and the JWT API's drizzle/ folder. The chat's first migration is generated from its own schema, in the next section.

The files the chat leans on directly are short, so here they are. The configuration schema refuses to start the app without a database URL and a signing secret of at least 32 bytes:

// src/config.ts
import { z } from 'zod';

export const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
  PORT: z.coerce.number().int().default(3000),
  DATABASE_URL: z.url(),
  // Signs the access tokens: at least 32 bytes.
  JWT_SECRET: z.string().min(32),
  // The browser origins allowed to call the API, comma-separated. None by default.
  CORS_ORIGINS: z
    .string()
    .default('')
    .transform((value) => value.split(',').map((origin) => origin.trim()).filter(Boolean))
    .pipe(z.array(z.url())),
});

export type Env = z.infer<typeof envSchema>;
Enter fullscreen mode Exit fullscreen mode

main.ts runs Nest on the Node adapter, turns on shutdown hooks (they matter for deploys, as the checklist at the end explains) and serves the OpenAPI document. The only change from the JWT API is the document's title:

// src/main.ts
import { ConsoleLogger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule, ObserveInstrument } from './app.module.js';
import type { Env } from './config.js';

const production = process.env.NODE_ENV === 'production';
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter(), {
  instrument: ObserveInstrument,
  logger: new ConsoleLogger({
    // One JSON object per line in production; readable text in development.
    json: production,
    // Masks these properties wherever they appear in a logged object.
    redact: ['password', 'authorization', 'accessToken', 'refreshToken'],
  }),
});
app.useSecurityHeaders();
app.enableShutdownHooks();

const config = app.get<ConfigService<Env, true>>(ConfigService);
app.enableCors({ origin: config.get('CORS_ORIGINS', { infer: true }) });

const document = new DocumentBuilder()
  .setTitle('Chat API')
  .setVersion('1.0')
  .addBearerAuth()
  .addSecurityRequirements('bearer')
  .build();
SwaggerModule.setup('docs', app, () => SwaggerModule.createDocument(app, document));

await app.listen(config.get('PORT', { infer: true }));
Enter fullscreen mode Exit fullscreen mode

The credential provider is what turns an access token into a user, over HTTP and, as we'll see, over the socket too. Its realm is the other rename, from 'notes' to 'chat'. User is the JWT API's { id, email, createdAt } interface from src/users/user.ts:

// src/auth/jwt-auth.provider.ts
import { Injectable } from '@nestjs/common';
import { AuthenticationRegistry, JwtBearerProvider, type JwtClaims } from '@nestjs/authentication';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';

@Injectable()
export class JwtAuth extends JwtBearerProvider<User> {
  constructor(
    private readonly usersRepository: UsersRepository,
    registry: AuthenticationRegistry,
  ) {
    // The key, issuer and audience come from the `accessToken` options.
    super({ realm: 'chat' });
    registry.registerProvider(this);
  }

  // Called once the signature, `exp`, `iss` and `aud` checked out.
  // Returning null (the user was deleted) rejects the token.
  validate({ sub }: JwtClaims) {
    return sub ? this.usersRepository.findById(sub) : null;
  }
}
Enter fullscreen mode Exit fullscreen mode

The test configuration sets the two required variables. The tests sign a short-lived token of their own with this JWT_SECRET, so it's worth knowing where it comes from:

// vitest.config.e2e.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    root: './',
    include: ['test/**/*.e2e-spec.ts'],
    env: {
      DATABASE_URL: 'postgres://unused-in-tests',
      JWT_SECRET: 'test-only-jwt-secret-of-at-least-32-bytes',
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Add the test script to package.json:

"test:e2e": "vitest run --config ./vitest.config.e2e.ts"
Enter fullscreen mode Exit fullscreen mode

The chat gets a database of its own:

$ docker run -d --name chat-db -e POSTGRES_PASSWORD=chat -e POSTGRES_DB=chat -p 5432:5432 postgres:17
Enter fullscreen mode Exit fullscreen mode

Its URL goes in .env, next to the signing secret:

# .env
DATABASE_URL=postgres://postgres:chat@localhost:5432/chat
# Generate with: openssl rand -base64 32
JWT_SECRET=
Enter fullscreen mode Exit fullscreen mode

Design the chat schema in PostgreSQL

The whole schema fits in one file. users and refresh_tokens are unchanged from the JWT API; rooms, room_members and messages are new:

// src/database/schema.ts
import { bigint, boolean, index, jsonb, pgTable, primaryKey, text, timestamp, uuid } from 'drizzle-orm/pg-core';

const at = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: text('email').notNull().unique(),
  passwordHash: text('password_hash').notNull(),
  createdAt: at('created_at').notNull().defaultNow(),
});

export const rooms = pgTable('rooms', {
  id: uuid('id').primaryKey().defaultRandom(),
  name: text('name').notNull(),
  createdAt: at('created_at').notNull().defaultNow(),
});

export const roomMembers = pgTable(
  'room_members',
  {
    roomId: uuid('room_id')
      .notNull()
      .references(() => rooms.id, { onDelete: 'cascade' }),
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    joinedAt: at('joined_at').notNull().defaultNow(),
  },
  (table) => [
    // Leads with the room: "is this user a member of this room?" is one index lookup.
    primaryKey({ columns: [table.roomId, table.userId] }),
    // For "the rooms of this user".
    index('room_members_user_id_idx').on(table.userId),
  ],
);

export const messages = pgTable(
  'messages',
  {
    // From a sequence, not a UUID: ids grow with time, so "before id X" is a page of history.
    id: bigint('id', { mode: 'number' }).primaryKey().generatedAlwaysAsIdentity(),
    roomId: uuid('room_id')
      .notNull()
      .references(() => rooms.id, { onDelete: 'cascade' }),
    authorId: uuid('author_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    body: text('body').notNull(),
    createdAt: at('created_at').notNull().defaultNow(),
  },
  // Serves the history query: one room's messages, newest first, from any id.
  (table) => [index('messages_room_id_id_idx').on(table.roomId, table.id)],
);

// What @nestjs/authentication keeps for refresh tokens, stored by their SHA-256.
export const refreshTokens = pgTable(
  'refresh_tokens',
  {
    id: text('id').primaryKey(),
    familyId: text('family_id').notNull(),
    userId: text('user_id').notNull(),
    createdAt: at('created_at').notNull(),
    expiresAt: at('expires_at').notNull(),
    familyExpiresAt: at('family_expires_at').notNull(),
    usedAt: at('used_at'),
    // A family is revoked when any of its tokens is.
    revoked: boolean('revoked').notNull().default(false),
    claims: jsonb('claims').$type<Record<string, unknown>>(),
  },
  (table) => [
    index('refresh_tokens_family_id_idx').on(table.familyId),
    index('refresh_tokens_user_id_idx').on(table.userId),
    index('refresh_tokens_family_expires_at_idx').on(table.familyExpiresAt),
  ],
);

export type Room = typeof rooms.$inferSelect;
export type Message = typeof messages.$inferSelect;
Enter fullscreen mode Exit fullscreen mode

Three choices in there carry the rest of the design:

  • Membership is its own table, keyed by room and then user. Every single message checks it, so that check has to be cheap: it's one lookup on the primary key, which starts with the room. The second index is for the opposite question, "which rooms is this user in".
  • Message ids come from a sequence, not from gen_random_uuid(). They grow in the order the database stores messages, so "the messages before id 120" is a well-defined page, and sorting by id is sorting by storage order. Random UUIDs don't sort like that.
  • (room_id, id) has one index covering both. The history query reads one room's messages from some id downwards, and that's a walk along this index no matter how long the room's history gets.

Generate the first migration and apply it (more in the docs' Migrations section):

$ npx drizzle-kit generate --name=chat
$ npx drizzle-kit migrate
Enter fullscreen mode Exit fullscreen mode

Rooms and members

Start with the schemas for everything a client can send, over REST and over the socket. Having both in one file makes it easy to see the whole input surface of the chat:

// src/chat/chat.schemas.ts
import { z } from 'zod';

// Over REST

export const createRoomSchema = z.object({
  name: z.string().trim().min(1).max(100),
});
export type CreateRoomDto = z.infer<typeof createRoomSchema>;

export const addMemberSchema = z.object({
  email: z.email(),
});
export type AddMemberDto = z.infer<typeof addMemberSchema>;

export const historyQuerySchema = z.object({
  // The oldest message id the client has; omit it for the newest page.
  before: z.coerce.number().int().positive().optional(),
  limit: z.coerce.number().int().min(1).max(100).default(50),
});
export type HistoryQuery = z.infer<typeof historyQuerySchema>;

// Over the socket

export const roomRefSchema = z.object({
  roomId: z.uuid(),
});
export type RoomRef = z.infer<typeof roomRefSchema>;

export const sendMessageSchema = z.object({
  roomId: z.uuid(),
  body: z.string().trim().min(1).max(4_000),
});
export type SendMessageDto = z.infer<typeof sendMessageSchema>;
Enter fullscreen mode Exit fullscreen mode

The rules for rooms are simple: any member can add another user by email, and any member can leave. Like the JWT API's notes service, the rooms service takes the signed-in user's id as its first argument:

// src/chat/rooms.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, asc, eq, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { roomMembers, rooms, users, type Room } from '../database/schema.js';

@Injectable()
export class RoomsService {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  /** Creates a room with its creator as the first member. */
  create(userId: string, name: string): Promise<Room> {
    return this.db.transaction(async (tx) => {
      const [room] = await tx.insert(rooms).values({ name }).returning();
      await tx.insert(roomMembers).values({ roomId: room.id, userId });
      return room;
    });
  }

  findMine(userId: string): Promise<Room[]> {
    return this.db
      .select({ id: rooms.id, name: rooms.name, createdAt: rooms.createdAt })
      .from(rooms)
      .innerJoin(roomMembers, eq(roomMembers.roomId, rooms.id))
      .where(eq(roomMembers.userId, userId))
      .orderBy(asc(rooms.name), asc(rooms.id));
  }

  /** A member adds another user, by email. Adding a member twice changes nothing. */
  async addMember(userId: string, roomId: string, email: string): Promise<void> {
    // One statement: the caller must be a member, and the user must exist.
    const added = await this.db
      .insert(roomMembers)
      .select((qb) =>
        qb
          .select({ roomId: roomMembers.roomId, userId: users.id })
          .from(roomMembers)
          .innerJoin(users, eq(users.email, normalize(email)))
          .where(this.membership(userId, roomId)),
      )
      .onConflictDoNothing()
      .returning({ userId: roomMembers.userId });
    if (added.length === 0) {
      // Not added: find out why, for the status code.
      await this.assertMember(userId, roomId);
      const [user] = await this.db
        .select({ id: users.id })
        .from(users)
        .where(eq(users.email, normalize(email)));
      if (!user) {
        throw new NotFoundException('User not found');
      }
      // Otherwise, they were a member already.
    }
  }

  async leave(userId: string, roomId: string): Promise<void> {
    const left = await this.db
      .delete(roomMembers)
      .where(this.membership(userId, roomId))
      .returning({ userId: roomMembers.userId });
    if (left.length === 0) {
      notFound();
    }
  }

  /** 404 unless the user is a member: other people's rooms are as missing as rooms that don't exist. */
  async assertMember(userId: string, roomId: string): Promise<void> {
    const [member] = await this.db
      .select({ one: sql`1` })
      .from(roomMembers)
      .where(this.membership(userId, roomId));
    if (!member) {
      notFound();
    }
  }

  private membership(userId: string, roomId: string) {
    return and(eq(roomMembers.roomId, roomId), eq(roomMembers.userId, userId));
  }
}

function notFound(): never {
  throw new NotFoundException('Room not found');
}

const normalize = (email: string) => email.trim().normalize('NFC').toLowerCase();
Enter fullscreen mode Exit fullscreen mode

The interesting method is addMember(), and it's interesting because of what it doesn't do. The obvious version checks that the caller is a member, then looks up the user, then inserts. That's three round trips, and the answers to the first two can change before the third one runs. Here it's a single INSERT ... SELECT: the row to insert is built from the caller's own membership row, joined with the user that the email names. If the caller isn't a member, or no user has that email, the SELECT produces nothing and nothing gets inserted. There's no gap between a check and a write. ON CONFLICT DO NOTHING turns adding someone twice into a no-op instead of a 500.

Only the unhappy path pays for extra queries. When nothing was inserted, addMember() looks again, purely to pick the right status code: 404 if the caller isn't in the room, 404 if the email is unknown, and 204 if the user was already a member.

Two more details. Someone else's room is a 404, exactly like a room that doesn't exist, so nobody can probe for valid room ids. And leaving is a DELETE with the membership in its WHERE clause; whether it returned a row tells us if there was anything to leave.

Store messages and paginate the history

Messages get a service of their own. The rule that makes the chat trustworthy lives here: posting a message checks the membership, and that check is the same statement that stores the message.

// src/chat/messages.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, desc, eq, lt, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { messages, roomMembers, type Message } from '../database/schema.js';
import type { HistoryQuery } from './chat.schemas.js';
import { RoomsService } from './rooms.service.js';

export interface MessagePage {
  /** Newest first. */
  messages: Message[];
  /** Pass as `before` for the next, older page; `null` on the oldest page. */
  nextBefore: number | null;
}

@Injectable()
export class MessagesService {
  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    private readonly roomsService: RoomsService,
  ) {}

  /** Stores a message, if its author is a member of the room. */
  async post(authorId: string, roomId: string, body: string): Promise<Message> {
    // The membership row is the source of the insert: a non-member's message,
    // or one sent the moment its author left, inserts nothing.
    const [message] = await this.db
      .insert(messages)
      .select((qb) =>
        qb
          .select({ roomId: roomMembers.roomId, authorId: roomMembers.userId, body: sql<string>`${body}`.as('body') })
          .from(roomMembers)
          .where(and(eq(roomMembers.roomId, roomId), eq(roomMembers.userId, authorId))),
      )
      .returning();
    if (!message) {
      throw new NotFoundException('Room not found');
    }
    return message;
  }

  /** A page of a room's history, older than `before`. */
  async history(userId: string, roomId: string, { before, limit }: HistoryQuery): Promise<MessagePage> {
    await this.roomsService.assertMember(userId, roomId);
    const rows = await this.db
      .select()
      .from(messages)
      .where(and(eq(messages.roomId, roomId), before ? lt(messages.id, before) : undefined))
      .orderBy(desc(messages.id))
      // One more than asked for: whether it comes back says if there's an older page.
      .limit(limit + 1);
    const page = rows.slice(0, limit);
    return { messages: page, nextBefore: rows.length > limit ? page[page.length - 1].id : null };
  }
}
Enter fullscreen mode Exit fullscreen mode

The membership row is the source of the insert

In SQL, post() is INSERT INTO messages ... SELECT ... FROM room_members WHERE room_id = $1 AND user_id = $2. For a member, the SELECT returns one row and one message is stored. For anyone else, it returns nothing and nothing is stored. Now think about a user who leaves the room while one of their messages is in flight: either the message is stored before the DELETE commits, or it inserts nothing. There's never a check that passed a moment ago and is stale by the time the write happens.

Keyset pagination for chat history

The history is a keyset page: WHERE room_id = $1 AND id < $before ORDER BY id DESC LIMIT n. It starts from the oldest message the client already has and walks the (room_id, id) index from there. OFFSET would be the wrong tool twice over. It reads and discards every newer message first, so old pages get slower as the room grows. And in a chat, new messages arrive while someone scrolls back, so every new message would shift the offset pages by one.

The query asks for one row more than the page size. Whether that extra row comes back tells us if there's an older page, so nextBefore is null on the last page rather than pointing the client at an empty one.

Reading the history checks the membership first, as a separate query. That's fine here, unlike in post(): it's a read, and nothing is written between the check and the query that could need undoing.

The Socket.IO gateway

In Nest, a gateway handles the messages clients send over a socket. We'll use Socket.IO, through @nestjs/platform-socket.io, rather than the plain ws library, for four reasons:

  • The access token can travel in the handshake. Browsers can't set an Authorization header on a WebSocket connection. A Socket.IO client sends the token in the auth payload of its handshake instead, and JwtBearerProvider reads it from there. So the gateway signs users in with the same tokens, and the same JwtAuth provider, as the REST routes.
  • Rooms are built in. Socket.IO keeps a set of sockets per room and can broadcast to one of them, which is exactly what a chat room needs.
  • Acknowledgments are built in. A client that sends a message gets the server's answer to that particular message. Here, that's the stored message with its id.
  • It scales out with an adapter. More on that in "Scale Socket.IO to more than one instance" below.

Once @nestjs/platform-socket.io is installed, Nest serves Socket.IO on the HTTP server's port, under /socket.io/, and that works with the Node adapter too. main.ts doesn't change.

Track presence per socket

Who has a room open is kept in memory, per socket rather than per user. A user with two tabs open should go offline when they close the second tab, not the first:

// src/chat/presence.service.ts
import { Injectable } from '@nestjs/common';

/** Who has each room open, on this instance: room id, then socket id, then user id. */
@Injectable()
export class PresenceService {
  private readonly rooms = new Map<string, Map<string, string>>();

  /** Whether this is the user's first socket in the room. */
  add(roomId: string, socketId: string, userId: string): boolean {
    const sockets = this.rooms.get(roomId) ?? new Map<string, string>();
    this.rooms.set(roomId, sockets);
    const first = !this.has(sockets, userId);
    sockets.set(socketId, userId);
    return first;
  }

  /** Removes one socket. Returns its user if that was their last socket in the room. */
  remove(roomId: string, socketId: string): string | undefined {
    const sockets = this.rooms.get(roomId);
    const userId = sockets?.get(socketId);
    if (!sockets || !userId) {
      return undefined;
    }
    sockets.delete(socketId);
    this.prune(roomId, sockets);
    return this.has(sockets, userId) ? undefined : userId;
  }

  /** Removes every socket of a user. Returns whether they had one. */
  removeUser(roomId: string, userId: string): boolean {
    const sockets = this.rooms.get(roomId);
    if (!sockets || !this.has(sockets, userId)) {
      return false;
    }
    for (const [socketId, user] of sockets) {
      if (user === userId) {
        sockets.delete(socketId);
      }
    }
    this.prune(roomId, sockets);
    return true;
  }

  online(roomId: string): string[] {
    return [...new Set(this.rooms.get(roomId)?.values())];
  }

  private has(sockets: Map<string, string>, userId: string): boolean {
    return [...sockets.values()].includes(userId);
  }

  private prune(roomId: string, sockets: Map<string, string>) {
    if (sockets.size === 0) {
      this.rooms.delete(roomId);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The gateway itself

This is the heart of the chat: connection, join, leave, message and typing, plus the hook the REST side calls when someone leaves a room:

// src/chat/chat.gateway.ts
import { UseFilters } from '@nestjs/common';
import { CurrentUser, WsAuthenticator, type JwtClaims } from '@nestjs/authentication';
import { Throttle, seconds } from '@nestjs/throttler';
import {
  ConnectedSocket,
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  type OnGatewayConnection,
} from '@nestjs/websockets';
import type { Server, Socket } from 'socket.io';
import type { User } from '../users/user.js';
import { ChatExceptionFilter } from './chat-exception.filter.js';
import { roomRefSchema, sendMessageSchema, type RoomRef, type SendMessageDto } from './chat.schemas.js';
import { MessagesService } from './messages.service.js';
import { PresenceService } from './presence.service.js';
import { RoomsService } from './rooms.service.js';

/** The socket.io room of a chat room: its open sockets, which receive its messages. */
const roomChannel = (roomId: string) => `room:${roomId}`;
/** Every socket of one user, on every instance. */
const userChannel = (userId: string) => `user:${userId}`;

@UseFilters(new ChatExceptionFilter())
@WebSocketGateway()
export class ChatGateway implements OnGatewayConnection {
  @WebSocketServer()
  private readonly server: Server;

  constructor(
    private readonly wsAuthenticator: WsAuthenticator,
    private readonly roomsService: RoomsService,
    private readonly messagesService: MessagesService,
    private readonly presence: PresenceService,
  ) {}

  async handleConnection(client: Socket) {
    // Registered first: socket.io empties `client.rooms` before "disconnect".
    client.on('disconnecting', () => this.closeRooms(client));
    // Closes the connection (and returns null) unless the handshake carries a valid access token.
    const auth = await this.wsAuthenticator.authenticateConnection(client);
    if (!auth) {
      return;
    }
    const { id } = auth.user as User;
    client.data.userId = id;
    await client.join(userChannel(id));
    // A connection lasts as long as its access token. The client then
    // reconnects with a fresh one, as it would send one with a request.
    const { exp } = auth.session as JwtClaims;
    if (exp) {
      const expiry = setTimeout(() => client.disconnect(true), exp * 1000 - Date.now());
      client.on('disconnect', () => clearTimeout(expiry));
    }
  }

  /** Opens a room: the socket receives its messages, typing and presence. */
  @SubscribeMessage('join')
  async join(
    @CurrentUser('id') userId: string,
    @ConnectedSocket() client: Socket,
    @MessageBody({ schema: roomRefSchema }) { roomId }: RoomRef,
  ) {
    await this.roomsService.assertMember(userId, roomId);
    await client.join(roomChannel(roomId));
    if (this.presence.add(roomId, client.id, userId)) {
      client.to(roomChannel(roomId)).emit('presence', { roomId, userId, online: true });
    }
    return { roomId, online: this.presence.online(roomId) };
  }

  /** Closes a room on this socket. The user stays a member. */
  @SubscribeMessage('leave')
  async leave(@ConnectedSocket() client: Socket, @MessageBody({ schema: roomRefSchema }) { roomId }: RoomRef) {
    await client.leave(roomChannel(roomId));
    this.wentAway(roomId, this.presence.remove(roomId, client.id));
    return { roomId };
  }

  @Throttle({ default: { limit: 10, ttl: seconds(10) } })
  @SubscribeMessage('message')
  async message(
    @CurrentUser('id') userId: string,
    @ConnectedSocket() client: Socket,
    @MessageBody({ schema: sendMessageSchema }) { roomId, body }: SendMessageDto,
  ) {
    // Stored first, then broadcast: nobody sees a message that a restart could lose.
    const message = await this.messagesService.post(userId, roomId, body);
    client.to(roomChannel(roomId)).emit('message', message);
    // The acknowledgment: the sender learns the message's id.
    return message;
  }

  @SubscribeMessage('typing')
  typing(
    @CurrentUser('id') userId: string,
    @ConnectedSocket() client: Socket,
    @MessageBody({ schema: roomRefSchema }) { roomId }: RoomRef,
  ) {
    // Only from a socket that opened the room, which checked the membership.
    if (client.rooms.has(roomChannel(roomId))) {
      client.to(roomChannel(roomId)).emit('typing', { roomId, userId });
    }
  }

  /** After a user leaves a room over REST: their open sockets stop receiving it. */
  removeFromRoom(roomId: string, userId: string) {
    this.server.in(userChannel(userId)).socketsLeave(roomChannel(roomId));
    if (this.presence.removeUser(roomId, userId)) {
      this.wentAway(roomId, userId);
    }
  }

  private closeRooms(client: Socket) {
    for (const channel of client.rooms) {
      if (channel.startsWith('room:')) {
        const roomId = channel.slice('room:'.length);
        this.wentAway(roomId, this.presence.remove(roomId, client.id));
      }
    }
  }

  private wentAway(roomId: string, userId: string | undefined) {
    if (userId) {
      this.server.to(roomChannel(roomId)).emit('presence', { roomId, userId, online: false });
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

There's a lot packed into that class, so let's go through it.

Authenticate WebSocket connections with JWT

Nest doesn't run guards on handleConnection(), so the handshake is authenticated by hand, with WsAuthenticator from @nestjs/authentication. authenticateConnection() runs the same credential providers the guard does, and disconnects any socket that didn't bring a valid access token (the docs cover it in GraphQL and WebSockets). On the client side, that looks like a connect event followed by a disconnect with the reason io server disconnect.

But the handshake isn't the gate on its own. Nest doesn't wait for handleConnection() to finish before it starts handling a socket's messages. What actually protects each message is the global authentication guard, which runs for every @SubscribeMessage() handler just as it does for every route. @CurrentUser('id') then reads the user of that message.

End the connection when the access token expires

This one is easy to miss. The token is checked once, at the handshake, and a socket can stay open for days. Without the timer in handleConnection(), a socket whose token expired would get a 401 for every message it sent, but it would keep receiving the room's messages for as long as it stayed open. So the gateway disconnects the socket when the token's exp passes, and the client reconnects with a fresh token, the same way it would send a fresh token with its next HTTP request. The "Try it" section shows the client side.

Check the membership on every message, not only on join

join checks the membership before the socket enters the room's channel, so only members ever receive a room's messages. That's not enough for sending, though. A client can emit a message for any room id, joined or not. That's why post() checks again, in the statement that stores the message.

Store first, then broadcast

If the process dies between storing and broadcasting, the message is already in the history, and every client finds it when it reconnects. The other order would show the room a message that a restart could lose.

The sender gets the acknowledgment, everyone else gets the broadcast. client.to(channel) reaches every socket in the room except the sending one, and that includes the sender's other tabs. Both carry the same message object, id included.

Typing is relayed, never stored

A typing indicator is worthless a few seconds later, so it never touches the database. The gateway only relays it from a socket that has joined the room, which means it passed the membership check.

Leaving over REST evicts every open socket

Each socket joins a channel for its user when it connects. That gives removeFromRoom() a way to reach all of a user's sockets at once, and with an adapter, on every instance.

Turn refusals into error events

Out of the box, Nest's WebSocket exception filter sends a client the message of a WsException, and nothing else. Anything else reaches the client as "Internal server error", and that includes the NotFoundException our services throw for the REST routes and the validation pipe's BadRequestException. A WsException that carries an object, like the authentication guard's 401, goes out without a cause saying which message it answers. So the gateway gets a filter that gives every refusal the same shape (see Exception filters):

// src/chat/chat-exception.filter.ts
import { type ArgumentsHost, Catch, HttpException } from '@nestjs/common';
import { BaseWsExceptionFilter, WsException } from '@nestjs/websockets';

/**
 * Sends each refusal to the client as an "exception" event with its status code, its message,
 * and the event and payload it refuses, so the client can tell which message failed.
 */
@Catch(HttpException, WsException)
export class ChatExceptionFilter extends BaseWsExceptionFilter {
  catch(exception: HttpException | WsException, host: ArgumentsHost) {
    const ws = host.switchToWs();
    const cause = { pattern: ws.getPattern(), data: ws.getData() };
    super.catch(new WsException({ status: 'error', ...bodyOf(exception), cause }), host);
  }
}

function bodyOf(exception: HttpException | WsException): object {
  if (exception instanceof WsException) {
    const error = exception.getError();
    return typeof error === 'string' ? { message: error } : error;
  }
  // The services' exceptions, and the validation pipe's, which the client
  // would otherwise get as "Internal server error".
  const response = exception.getResponse();
  return typeof response === 'string' ? { statusCode: exception.getStatus(), message: response } : response;
}
Enter fullscreen mode Exit fullscreen mode

Validation needs nothing extra. The JWT API's global StandardSchemaValidationPipe validates @MessageBody() against its schema, the same way it validates @Body(), so a malformed message never reaches a handler. A refused message gets no acknowledgment. Instead, the client receives an exception event, and its cause names the event and the payload that was refused. Here's a message whose body is only spaces:

{
  "status": "error",
  "message": ["body: Too small: expected string to have >=1 characters"],
  "error": "Bad Request",
  "statusCode": 400,
  "cause": { "pattern": "message", "data": { "roomId": "5122632a-7885-4d6a-a7b8-8f03f54a4a98", "body": "   " } }
}
Enter fullscreen mode Exit fullscreen mode

Rooms and history over REST

Not everything belongs on the socket. Creating rooms, adding members and reading the history are ordinary requests: they don't need an open connection, and on REST they keep the JWT API's validation, rate limits and OpenAPI document for free.

// src/chat/rooms.controller.ts
import { Body, Controller, Delete, Get, HttpCode, Param, Post, Query } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { z } from 'zod';
import { ChatGateway } from './chat.gateway.js';
import {
  addMemberSchema,
  createRoomSchema,
  historyQuerySchema,
  type AddMemberDto,
  type CreateRoomDto,
  type HistoryQuery,
} from './chat.schemas.js';
import { MessagesService } from './messages.service.js';
import { RoomsService } from './rooms.service.js';

const roomId = { schema: z.uuid() };

@Controller('rooms')
export class RoomsController {
  constructor(
    private readonly roomsService: RoomsService,
    private readonly messagesService: MessagesService,
    private readonly chatGateway: ChatGateway,
  ) {}

  @Post()
  create(@CurrentUser('id') userId: string, @Body({ schema: createRoomSchema }) { name }: CreateRoomDto) {
    return this.roomsService.create(userId, name);
  }

  @Get()
  findMine(@CurrentUser('id') userId: string) {
    return this.roomsService.findMine(userId);
  }

  @Post(':id/members')
  @HttpCode(204)
  addMember(
    @CurrentUser('id') userId: string,
    @Param('id', roomId) id: string,
    @Body({ schema: addMemberSchema }) { email }: AddMemberDto,
  ) {
    return this.roomsService.addMember(userId, id, email);
  }

  @Delete(':id/members/me')
  @HttpCode(204)
  async leave(@CurrentUser('id') userId: string, @Param('id', roomId) id: string) {
    await this.roomsService.leave(userId, id);
    this.chatGateway.removeFromRoom(id, userId);
  }

  @Get(':id/messages')
  history(
    @CurrentUser('id') userId: string,
    @Param('id', roomId) id: string,
    @Query({ schema: historyQuerySchema }) query: HistoryQuery,
  ) {
    return this.messagesService.history(userId, id, query);
  }
}
Enter fullscreen mode Exit fullscreen mode

POST /rooms/:id/members and DELETE /rooms/:id/members/me answer 204 No Content, since the client already knows what changed. Leaving also calls the gateway, so the user's open sockets stop receiving the room right away, instead of whenever they next reconnect.

The chat module puts the controller, the gateway and the three services together:

// src/chat/chat.module.ts
import { Module } from '@nestjs/common';
import { ChatGateway } from './chat.gateway.js';
import { MessagesService } from './messages.service.js';
import { PresenceService } from './presence.service.js';
import { RoomsController } from './rooms.controller.js';
import { RoomsService } from './rooms.service.js';

@Module({
  controllers: [RoomsController],
  providers: [ChatGateway, RoomsService, MessagesService, PresenceService],
})
export class ChatModule {}
Enter fullscreen mode Exit fullscreen mode

Rate-limit WebSocket messages per user

Here's a trap I'd expect most people to walk into. The JWT API registers ThrottlerGuard globally, and a global guard runs for gateway messages too, with the default throttler. Over a WebSocket, though, the "request" the throttler counts by is the socket, and a socket has no ip. So every client's messages land on one shared counter, and one noisy user blocks everyone.

The fix is a tracker for the default throttler that counts gateway messages per user. The rate-limiting chapter's WebSockets section does this with a subclass of the guard. The getTracker option gets the ExecutionContext as well (see Configuration), so it does the same job without one:

// src/chat/throttler-tracker.ts
import type { ExecutionContext } from '@nestjs/common';
import { normalizeIp } from '@nestjs/throttler';

/**
 * What the throttler counts by. Over WebSockets, `req` is the socket, which has no `ip`:
 * without this, every client's messages would share one counter.
 */
export function tracker(req: Record<string, any>, context: ExecutionContext): string {
  if (context.getType() === 'ws') {
    // The user that the handshake signed in, or the address until it has.
    return req.data.userId ?? normalizeIp(req.handshake.address);
  }
  return normalizeIp(req.ip);
}
Enter fullscreen mode Exit fullscreen mode

client.data.userId is set in handleConnection(), once the handshake is authenticated. With this tracker, every gateway event counts against the default limit of 100 per minute per user, join, leave and typing included. message has a tighter limit of its own, 10 every 10 seconds, from the @Throttle() on its handler. The 11th message gets an exception event with status 429, and the filter passes the throttler's message through.

The root module wires in the chat module and the tracker. Everything else is the JWT API's, with the default throttler now using tracker:

// src/app.module.ts
import { Module, StandardSchemaValidationPipe } from '@nestjs/common';
import { APP_GUARD, APP_PIPE } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthenticationModule } from '@nestjs/authentication';
import { DrizzleModule } from '@nestjs/drizzle';
import { createObserveModule } from '@nestjs/observe';
import { ThrottlerGuard, ThrottlerModule, minutes, normalizeIp } from '@nestjs/throttler';
import { drizzle } from 'drizzle-orm/node-postgres';
import { accountEmail } from './auth/account-email.js';
import { AuthModule } from './auth/auth.module.js';
import { ChatModule } from './chat/chat.module.js';
import { tracker } from './chat/throttler-tracker.js';
import { envSchema, type Env } from './config.js';
import { HealthModule } from './health/health.module.js';
import { UsersModule } from './users/users.module.js';

export const { ObserveModule, ObserveInstrument } = createObserveModule();

@Module({
  imports: [
    // First, so it shuts down last and still sends what the other modules did.
    ObserveModule.forRoot({
      // Empty until `npx @nestjs/observe link` writes the key pair into .env: the SDK then sends nothing.
      appKey: process.env.OBSERVE_APP_KEY ?? '',
      appSecret: process.env.OBSERVE_APP_SECRET ?? '',
      serviceId: 'chat-api',
    }),
    ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
    DrizzleModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        drizzle,
        connection: config.get('DATABASE_URL', { infer: true }),
      }),
    }),
    AuthenticationModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        accessToken: {
          key: config.get('JWT_SECRET', { infer: true }),
          issuer: 'chat-api',
          audience: 'chat-api',
          ttl: '15m',
        },
        refreshToken: { ttl: '30d', absoluteTtl: '90d' },
      }),
    }),
    ThrottlerModule.forRoot([
      // Per IP address on every route, and per user on the chat gateway.
      { name: 'default', ttl: minutes(1), limit: 100, getTracker: tracker },
      // Per email and IP address, wherever the request body names an account.
      {
        name: 'account',
        ttl: minutes(15),
        limit: 5,
        skipIf: (context) => !accountEmail(context.switchToHttp().getRequest()),
        getTracker: (req) => `${accountEmail(req)}|${normalizeIp(req.ip)}`,
      },
    ]),
    UsersModule,
    AuthModule,
    ChatModule,
    HealthModule,
  ],
  providers: [
    { provide: APP_PIPE, useClass: StandardSchemaValidationPipe },
    { provide: APP_GUARD, useClass: ThrottlerGuard },
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Scale Socket.IO to more than one instance

Everything so far runs on one instance. Put several behind a load balancer and three things that live in one process stop being enough:

  • Broadcasts. client.to(channel).emit() only reaches sockets connected to the same instance. A Redis adapter shares broadcasts, and socketsLeave(), between instances, so removeFromRoom() reaches a user's sockets wherever they're connected. As that chapter warns, Redis alone doesn't cover it: Socket.IO clients start with HTTP long-polling, and all of those requests have to reach the same instance. Either turn on sticky sessions at the load balancer, or connect with transports: ['websocket'], as the clients in this article do.
  • Presence. PresenceService only knows its own instance's sockets. To show who's online across instances, keep the same map in Redis, with an expiry per instance so a crashed instance's sockets disappear, or ask every instance with Socket.IO's fetchSockets(), which the Redis adapter supports.
  • Rate limits. The throttler counts in memory, so each instance counts on its own. Give it shared storage, such as Redis.

The messages themselves need nothing: they're in PostgreSQL, and every instance reads the same history. None of this multi-instance setup is exercised by the tests below; the links above cover each part.

Try it

Socket.IO has its own protocol on top of the WebSocket, so curl can't join a room. A small client in scripts/ can. It connects with an access token, joins a room, prints what the server sends, and sends each line you type as a message:

// scripts/chat.ts
// A terminal client for trying the chat: TOKEN=<access token> node scripts/chat.ts <room id>
import { createInterface } from 'node:readline';
import { io } from 'socket.io-client';

const roomId = process.argv[2];
const socket = io(process.env.CHAT_URL ?? 'http://localhost:3000', {
  // The access token, which JwtBearerProvider reads from the handshake.
  auth: { token: process.env.TOKEN },
  // Straight to a WebSocket, without long-polling first.
  transports: ['websocket'],
});

const print = (event: string) => (data: unknown) => console.log(event, JSON.stringify(data));

socket.on('connect', () => {
  // Rooms are opened per connection: open it again after every reconnect.
  socket.emit('join', { roomId }, print('joined'));
});
socket.on('message', print('message'));
socket.on('presence', print('presence'));
socket.on('typing', print('typing'));
socket.on('exception', print('exception'));
socket.on('disconnect', print('disconnect'));

// Each line is a message.
for await (const body of createInterface({ input: process.stdin })) {
  socket.emit('typing', { roomId });
  try {
    print('sent')(await socket.timeout(5000).emitWithAck('message', { roomId, body }));
  } catch {
    // Refused: the "exception" event says why.
  }
}
socket.close();
Enter fullscreen mode Exit fullscreen mode

Node.js 22.18 and later run a TypeScript file like this one directly, with no build step. Start the application:

$ npm run start
Enter fullscreen mode Exit fullscreen mode

We need three users: Ada and Bob, who will chat, and Eve, who won't be in the room. Ada creates a room and adds Bob. (Tokens, ids and timestamps are shortened here and in the rest of the transcripts.)

$ curl localhost:3000/auth/sign-up --json '{"email":"ada@example.com","password":"correct horse battery"}'
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"hpJMLcGsMXSATrZ2...","expiresIn":900}
$ ADA=eyJhbGciOiJIUzI1NiIs...
$ BOB=eyJhbGciOiJIUzI1NiIs...
$ EVE=eyJhbGciOiJIUzI1NiIs...
$ curl localhost:3000/rooms -H "Authorization: Bearer $ADA" --json '{"name":"general"}'
{"id":"5122632a-7885-4d6a-a7b8-8f03f54a4a98","name":"general","createdAt":"2026-11-19T22:08:55.613Z"}
$ ROOM=5122632a-7885-4d6a-a7b8-8f03f54a4a98
$ curl -i localhost:3000/rooms/$ROOM/members -H "Authorization: Bearer $ADA" --json '{"email":"bob@example.com"}'
HTTP/1.1 204 No Content
$ curl localhost:3000/rooms -H "Authorization: Bearer $BOB"
[{"id":"5122632a-7885-4d6a-a7b8-8f03f54a4a98","name":"general","createdAt":"2026-11-19T22:08:55.613Z"}]
Enter fullscreen mode Exit fullscreen mode

Bob opens the room in a second terminal. Then Ada opens it in the first, types a message, and Bob answers. The lines without an event name in front are what each of them typed. Bob's terminal:

$ TOKEN=$BOB node scripts/chat.ts $ROOM
joined {"roomId":"5122632a-...","online":["7154be3b-..."]}
presence {"roomId":"5122632a-...","userId":"092e1b0b-...","online":true}
typing {"roomId":"5122632a-...","userId":"092e1b0b-..."}
message {"id":1,"roomId":"5122632a-...","authorId":"092e1b0b-...","body":"Hi Bob","createdAt":"2026-11-19T22:08:58.259Z"}
Hi Ada
sent {"id":2,"roomId":"5122632a-...","authorId":"7154be3b-...","body":"Hi Ada","createdAt":"2026-11-19T22:08:59.252Z"}
Enter fullscreen mode Exit fullscreen mode

Ada's terminal, over the same few seconds:

$ TOKEN=$ADA node scripts/chat.ts $ROOM
joined {"roomId":"5122632a-...","online":["7154be3b-...","092e1b0b-..."]}
Hi Bob
sent {"id":1,"roomId":"5122632a-...","authorId":"092e1b0b-...","body":"Hi Bob","createdAt":"2026-11-19T22:08:58.259Z"}
typing {"roomId":"5122632a-...","userId":"7154be3b-..."}
message {"id":2,"roomId":"5122632a-...","authorId":"7154be3b-...","body":"Hi Ada","createdAt":"2026-11-19T22:08:59.252Z"}
Enter fullscreen mode Exit fullscreen mode

Every message reaches the other side as exactly the object its sender got back in the acknowledgment, id and all.

Eve isn't a member. Her token is valid, so she can connect, but she can neither open the room nor post to it:

$ TOKEN=$EVE node scripts/chat.ts $ROOM
exception {"status":"error","message":"Room not found","error":"Not Found","statusCode":404,"cause":{"pattern":"join","data":{"roomId":"5122632a-..."}}}
Let me in
exception {"status":"error","message":"Room not found","error":"Not Found","statusCode":404,"cause":{"pattern":"message","data":{"roomId":"5122632a-...","body":"Let me in"}}}
Enter fullscreen mode Exit fullscreen mode

Now the history, one message per page, newest first. nextBefore is the before for the next page, and null on the last one. Eve gets the same 404 over REST:

$ curl "localhost:3000/rooms/$ROOM/messages?limit=1" -H "Authorization: Bearer $ADA"
{"messages":[{"id":2,"roomId":"5122632a-...","authorId":"7154be3b-...","body":"Hi Ada","createdAt":"2026-11-19T22:08:59.252Z"}],"nextBefore":2}
$ curl "localhost:3000/rooms/$ROOM/messages?limit=1&before=2" -H "Authorization: Bearer $ADA"
{"messages":[{"id":1,"roomId":"5122632a-...","authorId":"092e1b0b-...","body":"Hi Bob","createdAt":"2026-11-19T22:08:58.259Z"}],"nextBefore":null}
$ curl "localhost:3000/rooms/$ROOM/messages?limit=1" -H "Authorization: Bearer $EVE"
{"message":"Room not found","error":"Not Found","statusCode":404}
Enter fullscreen mode Exit fullscreen mode

The last check is the edge case from the intro: a user who leaves with a tab still open. Bob leaves the room over REST while his client keeps running:

$ curl -i -X DELETE localhost:3000/rooms/$ROOM/members/me -H "Authorization: Bearer $BOB"
HTTP/1.1 204 No Content
Enter fullscreen mode Exit fullscreen mode

Ada's client sees him go:

presence {"roomId":"5122632a-...","userId":"7154be3b-...","online":false}
Enter fullscreen mode Exit fullscreen mode

And Bob's next message is refused, by the same INSERT ... SELECT that stores messages:

Still here?
exception {"status":"error","message":"Room not found","error":"Not Found","statusCode":404,"cause":{"pattern":"message","data":{"roomId":"5122632a-...","body":"Still here?"}}}
Enter fullscreen mode Exit fullscreen mode

Reconnect when the access token expires

A real client also has to handle the end of a connection. When the access token expires, the server disconnects the socket, and the client refreshes the token over REST and connects again. If you pass auth as a function, Socket.IO asks for the token before every connection attempt, so a reconnect always sends the current one. This goes in your web client, not in the API:

// web client (not part of the API)
const socket = io('https://chat.example.com', {
  // Called before every connection attempt, so a reconnect sends the current token.
  auth: (send) => send({ token: accessToken }),
  transports: ['websocket'],
});

socket.on('disconnect', async (reason) => {
  // The server ends the connection when its access token expires.
  if (reason === 'io server disconnect') {
    await refreshTokens(); // POST /auth/token/refresh, which sets accessToken
    socket.connect();
  }
});
Enter fullscreen mode Exit fullscreen mode

After the reconnect, the connect handler runs again and reopens the rooms: a room is joined per connection, not per user. One more thing for the client: messages can arrive in a different order than their ids, so show them sorted by id, and drop any you already have, such as a message that came with the history and then arrived live as well.

Test the WebSocket gateway end to end

The tests start the real application on a free port with app.listen(0) and connect to it with socket.io-client, the way a browser would. The database is PGlite, PostgreSQL running in-process, as in the JWT API's tests. That's a fair stand-in here because everything the chat guarantees comes from single statements, not from how concurrent transactions interleave, so a single connection tests it faithfully.

// test/chat.e2e-spec.ts
import { createHmac } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { PGlite } from '@electric-sql/pglite';
import { PasswordHasher } from '@nestjs/authentication';
import { getDrizzleToken } from '@nestjs/drizzle';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import { drizzle } from 'drizzle-orm/pglite';
import { migrate } from 'drizzle-orm/pglite/migrator';
import { io, type Socket } from 'socket.io-client';
import { AppModule } from '../src/app.module.js';

describe('Chat (e2e)', () => {
  const pglite = new PGlite(); // PostgreSQL in-process: no server to start
  let app: NestNodeApplication;
  let url: string;
  const sockets: Socket[] = [];

  beforeAll(async () => {
    const db = drizzle({ client: pglite });
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(getDrizzleToken())
      .useValue(db)
      // scrypt at the default cost takes 128 MiB and a few hundred ms per hash.
      .overrideProvider(PasswordHasher)
      .useValue(new PasswordHasher({ logN: 10 }))
      .compile();
    app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
    // A real server on a free port: the sockets connect to it like any client.
    await app.listen(0);
    url = await app.getUrl();
  });

  afterEach(() => {
    for (const socket of sockets.splice(0)) {
      socket.disconnect();
    }
  });

  afterAll(async () => {
    await app.close();
    await pglite.close();
  });

  let clients = 0;

  /** Signs a user up, and returns their id, the headers of their requests, and their access token. */
  async function signUp(name: string) {
    const signedUp = await app.inject({
      method: 'POST',
      url: '/auth/sign-up',
      payload: { email: `${name}@example.com`, password: 'correct horse battery' },
      // Sign-up is rate-limited per IP address: each user signs up from their own.
      remoteAddress: `10.0.0.${++clients}`,
    });
    const { accessToken } = signedUp.json<{ accessToken: string }>();
    const headers = { authorization: `Bearer ${accessToken}` };
    const { id } = (await app.inject({ method: 'GET', url: '/me', headers })).json<{ id: string }>();
    return { id, headers, accessToken };
  }

  /** A room with its creator and the other users as members. */
  async function createRoom(creator: Awaited<ReturnType<typeof signUp>>, ...members: string[]) {
    const res = await app.inject({
      method: 'POST',
      url: '/rooms',
      headers: creator.headers,
      payload: { name: 'general' },
    });
    const { id } = res.json<{ id: string }>();
    for (const name of members) {
      const added = await app.inject({
        method: 'POST',
        url: `/rooms/${id}/members`,
        headers: creator.headers,
        payload: { email: `${name}@example.com` },
      });
      expect(added.statusCode).toBe(204);
    }
    return id;
  }

  /** An access token like the API's own, that expires within two seconds. */
  function shortLivedToken(sub: string) {
    const now = Math.floor(Date.now() / 1000);
    const encode = (part: object) => Buffer.from(JSON.stringify(part)).toString('base64url');
    const claims = { sub, iss: 'chat-api', aud: 'chat-api', iat: now, exp: now + 2 };
    const unsigned = `${encode({ alg: 'HS256', typ: 'JWT' })}.${encode(claims)}`;
    return `${unsigned}.${createHmac('sha256', process.env.JWT_SECRET!).update(unsigned).digest('base64url')}`;
  }

  /** A socket.io client, as a browser would open it, with the access token in the handshake. */
  function open(token: string): Socket {
    const socket = io(url, { auth: { token }, transports: ['websocket'] });
    sockets.push(socket);
    return socket;
  }

  function connect(token: string): Promise<Socket> {
    const socket = open(token);
    return new Promise((resolve) => socket.on('connect', () => resolve(socket)));
  }

  /** The next `event` the socket receives. */
  function next<T = any>(socket: Socket, event: string): Promise<T> {
    return new Promise((resolve) => socket.once(event, resolve));
  }

  /** Sends a message and waits for the server's acknowledgment. */
  function send(socket: Socket, event: string, data: unknown) {
    return socket.timeout(2000).emitWithAck(event, data);
  }

  it('disconnects a client without a valid access token', async () => {
    const socket = open('not-a-token');
    expect(await next(socket, 'disconnect')).toBe('io server disconnect');
  });

  it('stores a message, then delivers it to the room', async () => {
    const ada = await signUp('ada');
    const bob = await signUp('bob');
    const roomId = await createRoom(ada, 'bob');
    const adaSocket = await connect(ada.accessToken);
    const bobSocket = await connect(bob.accessToken);
    await send(adaSocket, 'join', { roomId });
    const joined = await send(bobSocket, 'join', { roomId });
    expect(joined.online.sort()).toEqual([ada.id, bob.id].sort());

    const received = next(bobSocket, 'message');
    const ack = await send(adaSocket, 'message', { roomId, body: 'Hi Bob' });

    expect(await received).toEqual(ack);
    expect(ack).toMatchObject({ roomId, authorId: ada.id, body: 'Hi Bob' });
    const history = await app.inject({ method: 'GET', url: `/rooms/${roomId}/messages`, headers: bob.headers });
    expect(history.json().messages).toEqual([ack]);
  });

  it("refuses a non-member's message, and stores nothing", async () => {
    const carol = await signUp('carol');
    const eve = await signUp('eve');
    const roomId = await createRoom(carol);
    const eveSocket = await connect(eve.accessToken);

    const refused = next(eveSocket, 'exception');
    eveSocket.emit('message', { roomId, body: 'Let me in' });

    expect(await refused).toEqual({
      status: 'error',
      statusCode: 404,
      message: 'Room not found',
      error: 'Not Found',
      cause: { pattern: 'message', data: { roomId, body: 'Let me in' } },
    });
    const history = await app.inject({ method: 'GET', url: `/rooms/${roomId}/messages`, headers: carol.headers });
    expect(history.json().messages).toEqual([]);
    expect(
      (await app.inject({ method: 'GET', url: `/rooms/${roomId}/messages`, headers: eve.headers })).statusCode,
    ).toBe(404);
  });

  it('checks the membership on every message, not only on join', async () => {
    const dan = await signUp('dan');
    const fay = await signUp('fay');
    const roomId = await createRoom(dan, 'fay');
    const danSocket = await connect(dan.accessToken);
    const faySocket = await connect(fay.accessToken);
    await send(danSocket, 'join', { roomId });
    const cameOnline = next(danSocket, 'presence');
    await send(faySocket, 'join', { roomId });
    expect(await cameOnline).toEqual({ roomId, userId: fay.id, online: true });

    const wentOffline = next(danSocket, 'presence');
    const left = await app.inject({ method: 'DELETE', url: `/rooms/${roomId}/members/me`, headers: fay.headers });
    expect(left.statusCode).toBe(204);
    expect(await wentOffline).toEqual({ roomId, userId: fay.id, online: false });

    // Fay's socket is still connected, and still names the room.
    const refused = next(faySocket, 'exception');
    faySocket.emit('message', { roomId, body: 'Still here?' });
    expect(await refused).toMatchObject({ statusCode: 404 });

    // And it no longer receives the room's messages.
    const delivered: unknown[] = [];
    faySocket.on('message', (message) => delivered.push(message));
    await send(danSocket, 'message', { roomId, body: 'Bye Fay' });
    await send(faySocket, 'leave', { roomId }); // a round trip on Fay's connection
    expect(delivered).toEqual([]);
  });

  it('disconnects a client when its access token expires', async () => {
    const kim = await signUp('kim');
    const socket = open(shortLivedToken(kim.id));

    await next(socket, 'connect');
    expect(await next(socket, 'disconnect')).toBe('io server disconnect');
  });

  it('validates messages with the Zod schema', async () => {
    const gus = await signUp('gus');
    const roomId = await createRoom(gus);
    const socket = await connect(gus.accessToken);

    const refused = next(socket, 'exception');
    socket.emit('message', { roomId, body: '   ' });

    expect(await refused).toMatchObject({
      statusCode: 400,
      message: ['body: Too small: expected string to have >=1 characters'],
    });
  });

  it('pages through the history, newest first', async () => {
    const hal = await signUp('hal');
    const roomId = await createRoom(hal);
    const socket = await connect(hal.accessToken);
    const sent: number[] = [];
    for (const body of ['one', 'two', 'three', 'four', 'five']) {
      sent.push((await send(socket, 'message', { roomId, body })).id);
    }

    const ids: number[] = [];
    let before: number | null | undefined;
    do {
      const query = before ? `?limit=2&before=${before}` : '?limit=2';
      const page = await app.inject({ method: 'GET', url: `/rooms/${roomId}/messages${query}`, headers: hal.headers });
      const { messages, nextBefore } = page.json<{ messages: { id: number }[]; nextBefore: number | null }>();
      ids.push(...messages.map((message) => message.id));
      before = nextBefore;
    } while (before);

    expect(ids).toEqual(sent.reverse());
  });

  it('limits how fast each user sends messages', async () => {
    const ivy = await signUp('ivy');
    const jon = await signUp('jon');
    const roomId = await createRoom(ivy, 'jon');
    const ivySocket = await connect(ivy.accessToken);
    const jonSocket = await connect(jon.accessToken);

    const refused = next(ivySocket, 'exception');
    for (let i = 1; i <= 11; i++) {
      ivySocket.emit('message', { roomId, body: `Message ${i}` });
    }

    expect(await refused).toMatchObject({ statusCode: 429 });
    // Another user's messages are counted separately.
    expect(await send(jonSocket, 'message', { roomId, body: 'Hello' })).toMatchObject({ body: 'Hello' });
  });
});
Enter fullscreen mode Exit fullscreen mode

Three helpers in there exist because of traps in testing sockets:

  • open() hands back the socket before it connects. That lets the first test listen for disconnect from the very start. A socket the server refuses can receive its disconnect before the code after an await on connect even runs, and a test written that way hangs.
  • send() puts a timeout on the acknowledgment. A refused message never gets one, so without the timeout, a test that expects an acknowledgment would hang instead of failing.
  • shortLivedToken() signs a token exactly the way the API's accessToken options do (HS256, chat-api as issuer and audience, the test JWT_SECRET), set to expire within two seconds of the handshake.

Run the chat tests together with the JWT API's refresh-token store test, which needs a real PostgreSQL database of its own:

$ docker exec chat-db psql -U postgres -c "CREATE DATABASE chat_test"
$ TEST_DATABASE_URL=postgres://postgres:chat@localhost:5432/chat_test npm run test:e2e

 Test Files  2 passed (2)
      Tests  13 passed (13)
Enter fullscreen mode Exit fullscreen mode

A test suite is only worth something if it fails when the code is wrong, and these do. Store the message with a plain insert(messages).values() instead of the INSERT ... SELECT, and two tests fail: the non-member's message is stored and broadcast, and so is the message from the user who left. Remove the throttler's tracker, and the rate-limit test fails: Jon's very first message is refused, because Ivy used up the counter they share.

Production checklist for a Socket.IO chat

Everything in the JWT API's checklist applies here too. On top of it, for the chat:

  • Plan for several instances before you need them. The Redis adapter, shared presence and shared throttler storage from "Scale Socket.IO to more than one instance" are much easier to add before the second instance exists than after.
  • Expect every client to reconnect on each deploy. Shutdown hooks are on, so the SIGTERM of a deploy closes the open connections along with the application. Clients see transport close, not io server disconnect, and Socket.IO reconnects them by itself to an instance that's still running, where they reopen their rooms. Size your instances for that burst of handshakes.
  • End a banned or deleted user's connections yourself. The guard refuses their next message, but an open socket keeps receiving its rooms until its access token expires, up to 15 minutes later. Disconnect the sockets in the user's channel, the same way removeFromRoom() empties them out of a room.
  • Bound what one client can send. The Zod schema caps a message at 4,000 characters, and the throttler caps the rate. The IoAdapter also limits how many messages from one client are handled at once (see Limits).
  • Allow your web app's origin if it uses long-polling. WebSocket connections aren't subject to CORS, but Socket.IO's long-polling requests are. If your clients don't connect with transports: ['websocket'], pass a cors option with your web app's origin to @WebSocketGateway().
  • Keep the history query on its index. messages_room_id_id_idx serves every page. A history that filters on anything else, an author or a search term, needs an index of its own, or a search engine.
  • Give production its own Observe key pair. I create one on the project's API Keys page and set it as OBSERVE_APP_KEY and OBSERVE_APP_SECRET in the platform's environment, because start:prod doesn't load .env. NestJS Observe then reports each message handled by @SubscribeMessage() as a request with the ws protocol, under an operation id of the gateway class and the pattern, such as ChatGateway:message. Connections and disconnections aren't reported (see WebSocket gateways).

What's next

Where I'd take the chat from here:

  • Notify members who aren't connected, by email or push, outside the request: Mail and Queues.
  • Give rooms owners and moderators, with permissions checked per room: Authorization.
  • Share broadcasts between instances: Adapters.
  • See slow history pages and refused messages in production: Observability.

What I like about building this in Nest is that the socket didn't get a second set of rules. The gateway reuses the REST side's access tokens, its global authentication guard, its validation pipe and Zod schemas, and its throttler, and the services that enforce membership are the same ones the controllers call. The only WebSocket-specific code is the part that really is specific: the handshake, the expiry timer, the rooms and the error shape.

The docs version of this article, kept up to date, is Build a real-time chat backend in Node.js. It builds on Build a REST API with JWT authentication, which covers the sign-in side in full.

Top comments (0)