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 

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>; 

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 })); 

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; } } 

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', }, }, }); 

Add the test script to package.json:

"test:e2e": "vitest run --config ./vitest.config.e2e.ts" 

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 

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= 

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; 

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 

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>; 

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 'dri...
Source:https://dev.to/nestjs/how-to-build-a-real-time-chat-backend-in-nodejs-with-nestjs-socketio-and-postgresql-29o2