Build a Real-Time Chat Server With Node.js
Build a real-time chat server with Node.js using Server-Sent Events and fetch, with rooms, history, heartbeats and a plain browser client.

When people hear "real-time chat" they reach for a WebSocket library, and that is often right. But a chat room has an asymmetry that a WebSocket hides: each client sends a message now and then, and receives every message from everyone all the time. Sending is an ordinary request. Only receiving needs a long-lived connection, and for one-way streams from server to browser, Server-Sent Events (SSE) are built into every browser and into Node.js without a package. This post builds a chat server on Node.js 26 with node:http, using POST for sending and SSE for receiving, with rooms, a short history, heartbeats and a client you can open in a browser.
Why SSE is enough here
SSE is a plain HTTP response that never ends. The server sends text/event-stream and writes lines of the form data: ... followed by a blank line. The browser's EventSource parses them, and, unlike a raw socket, reconnects by itself if the connection drops, sending the Last-Event-ID header so the server can resume. You get reconnection and resume for free, and the protocol passes through ordinary HTTP proxies.
The trade-off is direction. SSE carries data one way, server to client, and browsers limit a single origin to about six open HTTP/1.1 connections across tabs, which makes SSE awkward without HTTP/2. If you need binary frames, very high message rates or a client that sends constantly, use WebSockets. For chat, notifications and live dashboards, SSE is simpler.
The room model
Keep the state in memory. A room has a list of connected response objects and a bounded history. Each message gets an increasing numeric id, which doubles as the SSE event id.
const HISTORY = 50;
const rooms = new Map();
let nextId = 1;
export function getRoom(name) {
let room = rooms.get(name);
if (!room) {
room = { clients: new Set(), history: [] };
rooms.set(name, room);
}
return room;
}
export function post(name, user, text) {
const room = getRoom(name);
const message = { id: nextId++, user, text, at: Date.now() };
room.history.push(message);
if (room.history.length > HISTORY) room.history.shift();
for (const res of room.clients) send(res, message);
return message;
}
export function send(res, message) {
res.write(`id: ${message.id}\nevent: message\ndata: ${JSON.stringify(message)}\n\n`);
}
export function replay(res, name, afterId) {
for (const message of getRoom(name).history) {
if (message.id > afterId) send(res, message);
}
}post appends to the history, trims it to 50 messages and writes to every connected client. replay sends what a client missed. A new visitor passes afterId of 0 and gets the whole bounded history. A reconnecting EventSource sends Last-Event-ID, and the same function fills the gap. The JSON.stringify output never contains a raw newline, which matters because a newline inside a data: line would end the field early.
The SSE endpoint
The stream route sets the headers, registers the response in the room and cleans up when the client goes away.
import { getRoom, replay } from "./rooms.js";
export function stream(req, res, roomName) {
res.writeHead(200, {
"content-type": "text/event-stream",
"cache-control": "no-cache",
connection: "keep-alive",
"x-accel-buffering": "no",
});
res.write("retry: 3000\n\n");
const last = Number(req.headers["last-event-id"] ?? 0) || 0;
replay(res, roomName, last);
const room = getRoom(roomName);
room.clients.add(res);
const beat = setInterval(() => res.write(": ping\n\n"), 25_000);
req.on("close", () => {
clearInterval(beat);
room.clients.delete(res);
});
}Each piece has a purpose. retry: 3000 tells the browser to wait three seconds before reconnecting. The x-accel-buffering: no header stops nginx from buffering the stream, which would otherwise hold events back until a buffer fills, a failure that looks like "chat works locally and lags in production". The heartbeat, a comment line that starts with a colon, keeps idle connections from being closed by proxies and load balancers that drop silent sockets, commonly after 60 seconds. And req.on("close") removes the client, because forgetting that line is how an SSE server leaks a response object per visitor until it runs out of memory.
The send route and the server
Sending is a normal POST with a JSON body. Validation matters more than usual here, because whatever a client sends is relayed to everyone else.
import { createServer } from "node:http";
import { stream } from "./stream.js";
import { post } from "./rooms.js";
import { readFile } from "node:fs/promises";
const page = await readFile(new URL("./index.html", import.meta.url));
async function readJson(req) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > 2048) throw new RangeError("too large");
chunks.push(chunk);
}
return JSON.parse(Buffer.concat(chunks).toString());
}
createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost");
const match = url.pathname.match(/^\/rooms\/([a-z0-9-]{1,32})\/(stream|messages)$/);
if (req.method === "GET" && url.pathname === "/") {
res.writeHead(200, { "content-type": "text/html" });
return res.end(page);
}
if (!match) {
res.writeHead(404);
return res.end();
}
const [, room, kind] = match;
if (req.method === "GET" && kind === "stream") return stream(req, res, room);
if (req.method === "POST" && kind === "messages") {
try {
const { user, text } = await readJson(req);
const cleanUser = String(user ?? "").trim().slice(0, 24);
const cleanText = String(text ?? "").trim().slice(0, 500);
if (!cleanUser || !cleanText) {
res.writeHead(422);
return res.end("user and text are required");
}
post(room, cleanUser, cleanText);
res.writeHead(204);
return res.end();
} catch {
res.writeHead(400);
return res.end("bad request");
}
}
res.writeHead(405);
res.end();
}).listen(3000, () => console.log("chat on http://localhost:3000"));The room name is restricted by the regular expression to lowercase letters, digits and hyphens, so a client cannot create a room called __proto__ or a name with a slash. The server trims and truncates the fields instead of trusting the client's limits. And 204 after a post means "accepted, nothing to return": the sender sees its own message arrive through the stream like everyone else's, which keeps one code path for rendering.
The browser client
The client is one HTML file. It opens an EventSource, appends each message and posts with fetch. It uses textContent, never innerHTML, because a chat message is untrusted input and assigning it as HTML would let any user run script in everyone else's browser.
<!doctype html>
<meta charset="utf-8">
<title>Chat</title>
<ul id="log"></ul>
<form id="form">
<input id="user" placeholder="name" size="10" required>
<input id="text" placeholder="message" size="40" required>
<button>Send</button>
</form>
<script>
const room = location.hash.slice(1) || "lobby";
const log = document.getElementById("log");
const source = new EventSource(`/rooms/${room}/stream`);
source.addEventListener("message", (event) => {
const m = JSON.parse(event.data);
const li = document.createElement("li");
li.textContent = `${m.user}: ${m.text}`;
log.append(li);
});
document.getElementById("form").addEventListener("submit", async (event) => {
event.preventDefault();
const user = document.getElementById("user").value;
const text = document.getElementById("text");
await fetch(`/rooms/${room}/messages`, {
method: "POST",
body: JSON.stringify({ user, text: text.value }),
});
text.value = "";
});
</script>Open http://localhost:3000/#general in two tabs and the messages appear in both. The fragment after the hash selects the room, so #general and #random are separate conversations.
Watching the stream
You can see the raw protocol with curl, which is the fastest way to debug SSE.
curl -N localhost:3000/rooms/general/stream &
curl -s -X POST localhost:3000/rooms/general/messages -d '{"user":"ana","text":"hello"}'retry: 3000
id: 1
event: message
data: {"id":1,"user":"ana","text":"hello","at":1790000000000}
The -N flag turns off curl's own buffering. The at value is a millisecond timestamp, so yours will differ. After 25 seconds of silence you would also see : ping lines.
Testing reconnect
Stop the server, start it again and watch the browser. EventSource retries after three seconds. Because history lives in memory, the restarted server has no messages and ids restart at 1, so a client that remembers id 40 asks for messages after 40 and sees nothing until the counter passes it. That is a real bug in this design, not a quirk. Persist the history and the counter, or reset clients by sending a new event: reset after a restart, if you need correct resume across restarts.
Where this design stops
A single process holds all connections, so it cannot scale across machines without a shared channel. The usual fix is a message broker such as Redis pub/sub: each server subscribes, and post publishes instead of writing directly. There is also no authentication, so anyone can post as anyone, and no rate limit, so one client can flood a room. Add a signed session cookie and a per-user limit before this faces the public internet.
Each open stream also costs a socket and some memory. Node.js handles tens of thousands of idle connections on a modest machine, but operating system file descriptor limits are the first wall you hit, and ulimit -n is the setting to raise.
Operating it
A chat server that works on a laptop meets three problems in production, and all of them are visible before launch if you look. The first is slow clients. res.write returns false when the socket's buffer is full, which happens when a phone on a poor connection cannot keep up. If you ignore that, Node.js keeps queuing messages in memory for that one client, and a handful of stuck connections can grow the process by hundreds of megabytes. The fix is to check the return value and drop or skip clients that fall behind, because a chat client that missed messages can reconnect and replay from history, while a server that ran out of memory cannot.
The second is deploys. Every restart disconnects every client at once, and every EventSource then reconnects three seconds later, all together. That burst is called a thundering herd. Adding a random delay to the retry value per client spreads it out, and so does draining the old process gradually.
The third is observability. Count connected clients per room and messages per second, and expose them on a metrics route. A stuck room shows up as a client count that only ever rises, which is the signature of a missing close handler, and you want to see that on a graph before you see it in an out-of-memory crash.
Finally, think about moderation early. Anything relayed to everyone needs a way to mute a user, delete a message and cap a room's size. Those features are far easier to add while messages have ids and a single post function that every message passes through, and this design already gives you both.


