You send a chat message and wait. Nothing happens. You refresh the page, and there it is, three messages late. 😅

That's what happens when a "live" feature is built on plain HTTP alone. The browser has to keep asking, "Anything new yet?" That's slow, wasteful, and a little embarrassing.

So how do apps like chats, live dashboards, and multiplayer games update instantly? Most of them use WebSockets. In this post, you'll learn what WebSockets are and build the same real-time chat server twice, once with Express and once with NestJS, saving messages in MongoDB. 🚀

What Is WebSockets?

WebSockets is a way for a browser and a server to keep one connection open and talk to each other at any time.

Think of regular HTTP like sending letters. You write a letter (request), the server writes back (response), and the conversation ends. If you want more, you send another letter.

A WebSocket is more like a phone call. Once connected, both sides can speak whenever they like, and nobody has to hang up and redial.

Technically, the connection starts as a normal HTTP request. The client asks to "upgrade" it, and if the server agrees, the same connection becomes a WebSocket.

A quick note about Socket.IO 💡

In this tutorial, we'll use Socket.IO. It's a library built on top of WebSockets, and it adds helpful things like rooms, automatic reconnection, and event names.

One thing to know: Socket.IO is not a plain WebSocket server. It uses its own protocol on top, so a Socket.IO server needs a Socket.IO client. A raw new WebSocket(...) in the browser won't work with it.

Why WebSockets Matter

Real-time features are everywhere, and users now expect them:

  • Chat and support widgets
  • Live notifications
  • Collaborative tools
  • Dashboards that update on their own

With WebSockets, the server can push data the moment something happens. The client doesn't have to keep asking. That means less repeated requests and a smoother experience for users.

It's also a great skill to learn. Once you understand events and connections, you can build many kinds of live features.

Benefits of WebSockets (with Real Examples)

  1. Instant updates
    A new chat message appears for everyone in the room right away, with no refresh.

  2. Two-way communication
    The client can send events to the server, and the server can send events to the client. A typing indicator is a good example.

  3. Less repeated asking
    Instead of calling GET /messages every few seconds, you keep one open connection and wait for events.

  4. Rooms and targeted messages (with Socket.IO)
    You can send a message only to people in a specific room, like general or support.

  5. Reconnection help (with Socket.IO)
    If someone's Wi-Fi drops for a moment, Socket.IO tries to reconnect by default. 🔧

HTTP Polling vs WebSockets

HTTP polling WebSockets
How it works Client keeps asking the server One open connection, both sides can send
Updates Delayed by the polling interval Pushed as they happen
Simplicity Very easy to start Needs a bit more setup
Good for Data that changes rarely Chat, live feeds, collaboration

Polling isn't "bad." For data that changes once in a while, it can be perfectly fine. WebSockets shine when updates are frequent and need to feel instant.

What We're Building

A small chat server where:

  • A user joins a room
  • They receive the last 20 messages from MongoDB
  • Any new message is saved to MongoDB and sent to everyone in that room

The events we'll use are the same in both versions:

Event Direction Purpose
join client → server Join a room
history server → client Send the last messages
chat:send client → server Send a new message
chat:message server → clients Broadcast a saved message

Because both servers use the same events, one client can talk to either of them.

You'll need Node.js, pnpm (npm works too), and MongoDB running locally or a connection string from MongoDB Atlas.

Part 1: The Express + Socket.IO + MongoDB Server

Setup

mkdir chat-express && cd chat-express pnpm init pnpm add express socket.io mongoose pnpm add -D typescript tsx @types/express @types/node npx tsc --init 

The code

Create src/server.ts:

import express from "express"; import { createServer } from "node:http"; import { Server } from "socket.io"; import mongoose, { Schema, model } from "mongoose"; // 1. MongoDB model const messageSchema = new Schema( { room: { type: String, required: true, index: true }, username: { type: String, required: true, trim: true, maxlength: 30 }, text: { type: String, required: true, trim: true, maxlength: 500 }, }, { timestamps: true } ); const Message = model("Message", messageSchema); // 2. Express + HTTP server + Socket.IO const app = express(); const httpServer = createServer(app); const io = new Server(httpServer, { cors: { origin: "http://localhost:3000" }, // change to your client URL }); app.get("/health", (_req, res) => { res.json({ ok: true }); }); // 3. Socket events io.on("connection", (socket) => { console.log("Connected:", socket.id); socket.on("join", async (room: string) => { await socket.join(room); const latest = await Message.find({ room }) .sort({ createdAt: -1 }) .limit(20) .lean(); socket.emit("history", latest.reverse()); }); socket.on( "chat:send", async (payload: { room: string; username: string; text: string }) => { try { const saved = await Message.create(payload); io.to(payload.room).emit("chat:message", saved.toObject()); } catch (error) { socket.emit("chat:error", "Message could not be saved."); } } ); socket.on("disconnect", () => { console.log("Disconnected:", socket.id); }); }); // 4. Connect to MongoDB, then start listening async function start() { await mongoose.connect( process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017/chat-demo" ); httpServer.listen(3001, () => { console.log("Express + Socket.IO running on http://localhost:3001"); }); } start().catch((err) => { console.error("Failed to start server:", err); process.exit(1); }); 

Run it:

npx tsx src/server.ts 

What's happening here?

  • Express handles normal HTTP routes, like /health.
  • We wrap Express in a Node http server so Socket.IO can share the same port.
  • Each socket is one connected client.
  • socket.join(room) puts that client in a room, and io.to(room).emit(...) sends only to that room.
  • We save first, then broadcast, so what users see is what's stored.

Part 2: The NestJS + Socket.IO + MongoDB Server

NestJS has built-in support for WebSockets through gateways. A gateway is a class that listens for socket events, a bit like a controller does for HTTP routes.

Setup

pnpm add -g @nestjs/cli nest new chat-nest cd chat-nest pnpm add @nestjs/websockets @nestjs/platform-socket.io @nestjs/mongoose mongoose 

Then generate the pieces:

nest g module chat nest g service chat nest g gateway chat 

The schema

src/chat/message.schema.ts:

import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"; import { HydratedDocument } from "mongoose"; export type MessageDocument = HydratedDocument<Message>; @Schema({ timestamps: true }) export class Message { @Prop({ required: true, index: true }) room: string; @Prop({ required: true, trim: true, maxlength: 30 }) username: string; @Prop({ required: true, trim: true, maxlength: 500 }) text: string; } export const MessageSchema = SchemaFactory.createForClass(Message); 

The service

src/chat/chat.service.ts:

import { Injectable } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; import { Model } from "mongoose"; import { Message, MessageDocument } from "./message.schema"; @Injectable() export class ChatService { constructor( @InjectModel(Message.name) private messageModel: Model<MessageDocument> ) {} async getHistory(room: string) { const latest = await this.messageModel .find({ room }) .sort({ createdAt: -1 }) .limit(20) .lean(); return latest.reverse(); } async save(data: { room: string; username: string; text: string }) { const saved = await this.messageModel.create(data); return saved.toObject(); } } 

The gateway

src/chat/chat.gateway.ts:

import { ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer, } from "@nestjs/websockets"; import { Server, Socket } from "socket.io"; import { ChatService } from "./chat.service"; @WebSocketGateway({ cors: { origin: "http://localhost:3000" }, // change to your client URL }) export class ChatGateway { @WebSocketServer() server: Server; constructor(private readonly chatService: ChatService) {} @SubscribeMessage("join") async handleJoin( @MessageBody() room: string, @ConnectedSocket() client: Socket ) { await client.join(room); const history = await this.chatService.getHistory(room); client.emit("history", history); } @SubscribeMessage("chat:send") async handleSend( @MessageBody() payload: { room: string; username: string; text: string } ) { const saved = await this.chatService.save(payload); this.server.to(payload.room).emit("chat:message", saved); } } 

The module

src/chat/chat.module.ts:

import { Module } from "@nestjs/common"; import { MongooseModule } from "@nestjs/mongoose"; import { ChatGateway } from "./chat.gateway"; import { ChatService } from "./chat.service"; import { Message, MessageSchema } from "./message.schema"; @Module({ imports: [ MongooseModule.forFeature([{ name: Message.name, schema: MessageSchema }]), ], providers: [ChatGateway, ChatService], }) export class ChatModule {} 

And in src/app.module.ts, connect MongoDB and import the chat module:

import { Module } from "@nestjs/common"; import { MongooseModule } from "@nestjs/mongoose"; import { ChatModule } from "./chat/chat.module"; @Module({ imports: [ MongooseModule.forRoot( process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017/chat-demo" ), ChatModule, ], }) export class AppModule {} 

Start it with:

pnpm start:dev 

By default, a Nest gateway shares the HTTP port of your app. A fresh Nest app listens on port 3000 unless you change it in main.ts, so pick a port that doesn't clash with your client.

Test Either Server with One Client

Install the client in any folder:

pnpm add socket.io-client 

Then use this small script (adjust the URL and port for the server you're testing):

import { io } from "socket.io-client"; const socket = io("http://localhost:3001"); socket.on("connect", () => { socket.emit("join", "general"); socket.emit("chat:send", { room: "general", username: "Hamid", text: "Hello from the client! 👋", }); }); socket.on("history", (messages) => console.log("History:", messages)); socket.on("chat:message", (msg) => console.log("New message:", msg)); 

Run it, then check your MongoDB collection. You should see the saved message. ✅

Express vs NestJS for WebSockets

Neither is "better." They suit different situations.

Express + Socket.IO NestJS Gateway
Setup Fewer files, quick to start More structure, more files
Style You wire things yourself Decorators, modules, dependency injection
Good for Small servers, prototypes, learning the basics Larger apps with many features and teammates
Learning curve Gentler Steeper at first

If you're learning how sockets work, start with Express. If your project will grow, NestJS keeps things organized.

Best Tips (Do's and Don'ts)

Do:

  • ✅ Validate every incoming payload. Anyone can emit events to your server.
  • ✅ Set a specific CORS origin instead of allowing everything.
  • ✅ Use rooms so people only receive what's relevant to them.
  • ✅ Handle errors and send a friendly chat:error event back.
  • ✅ Keep event names consistent, like chat:send and chat:message.

Don't:

  • ❌ Trust the username sent by the client in a real app. Use authentication instead.
  • ❌ Store secrets or connection strings directly in code. Use environment variables.
  • ❌ Load your entire message history. Use limit and pagination.

A small practical tip: in production, add proper validation. In NestJS, you can use DTOs with class-validator. In Express, a schema validator like Zod works well.

Common Mistakes People Make

1. Connecting with a plain WebSocket client
A Socket.IO server expects a Socket.IO client. If you get connection errors, check that both sides use the same library.

2. Calling app.listen() instead of httpServer.listen() in Express
If Socket.IO is attached to httpServer but you start app, the socket server never receives connections. This one is easy to miss. 👀

3. Forgetting CORS
The browser blocks the connection and the console shows a CORS error. Set the cors.origin option to your client URL.

4. Broadcasting before saving
If the database write fails after you've already broadcast, users see messages that don't exist. Save first, then emit.

5. Forgetting to join a room before expecting room messages
Messages sent with io.to(room) only reach sockets that joined that room.

6. Port clashes in NestJS
A new Nest app and a React or Next.js client often both want port 3000. Change one of them.

Conclusion

WebSockets keep a connection open so your server and clients can talk instantly, like a phone call instead of letters. With Socket.IO, rooms and reconnection come built in. With MongoDB, your chat history survives restarts.

You've now seen the same real-time chat server in Express for a quick, simple setup and in NestJS for a structured one. Pick the one that fits your project, then try adding typing indicators, authentication, or message pagination. 💡

If this helped, you'll find more practical dev guides at hamidrazadev.com. Feel free to share it with a friend who's learning real-time apps, and tell me in the comments which version you'd build first. 😊