Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: A Real-Time Chat with WebSockets and KV

Build a real-time chat server in Deno. Use WebSockets for rooms, Deno KV for message history, a rate limiter, input validation and BroadcastChannel to link several server instances, plus the browser client.

Chat is the textbook real-time application. Messages must reach everyone in a room within moments, people join and leave all the time, newcomers want to see recent history, and a few bad actors will try to flood the room. This project puts together WebSockets, Deno KV for history, validation, and rate limiting into one working design.

You will build the core as plain testable logic first (rooms, history, limits), then wire it to real sockets, and finally make it work across several server instances.

The runnable code separates the chat logic from the network. Sockets are replaced by small stand-in objects with the same send, readyState and close members as a real WebSocket, and MiniKv stands in for Deno KV, so all of it runs on Node 24 here. The Deno server code that attaches real sockets is shown read-only below.

Requirements and design

  • Users connect to a room: ws://host/ws?room=general&name=Ada.
  • Everyone in the room receives messages, joins and leaves.
  • A newcomer receives the last 20 messages first.
  • Messages are 1 to 300 characters; at most 5 messages per 10 seconds per user.
  • Messages persist in KV, so history survives restarts.
flowchart LR
  A["Browser A"] -- "WebSocket" --> S1["Server instance 1"]
  B["Browser B"] -- "WebSocket" --> S2["Server instance 2"]
  S1 -- "save" --> K[("Deno KV history")]
  S2 -- "save" --> K
  S1 <-->|"BroadcastChannel"| S2

Each instance holds only its own sockets. KV stores history; a broadcast channel carries new messages between instances.

KV layout

TEXT
["chat", room, timestamp, id]  -> { id, room, from, text, at }

Timestamp as the third key part means a reverse prefix list with limit: 20 returns the 20 newest messages directly. The id keeps two messages in the same millisecond apart.

The chat core

ChatRoomHub knows nothing about networks. It receives events (join, message, leave) and calls send on whatever objects it is given. That makes it simple to test and to reuse behind WebSockets, SSE or anything else.

Node.js Rooms, history, validation and rate limiting

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

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

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

Note the design choices in the core:

  • Validation first. Nothing is stored or broadcast before the message passes the checks, and errors go only to the sender.
  • The history is part of join, so a newcomer never sees an empty room by accident.
  • Names and room ids are sanitized. A room name is matched against a strict pattern, since it becomes part of a KV key.
  • The clock is injected (now), so tests can move time forward to check the rate-limit window.

Connecting real WebSockets

The Deno side is only glue between sockets and the hub:

TypeScript
import { ChatHub } from "./chat_hub.ts";

const kv = await Deno.openKv();
const hub = new ChatHub(kv);

Deno.serve({ port: 8000 }, async (req) => {
  const url = new URL(req.url);

  if (url.pathname === "/ws") {
    if (req.headers.get("upgrade") !== "websocket") {
      return new Response("WebSocket required", { status: 426 });
    }
    const room = url.searchParams.get("room") ?? "general";
    const name = url.searchParams.get("name") ?? "guest";

    const { socket, response } = Deno.upgradeWebSocket(req, { idleTimeout: 30 });
    socket.onopen = () => hub.join(socket, room, name);
    socket.onmessage = (e) => hub.message(socket, room, String(e.data));
    socket.onclose = () => hub.leave(socket, room);
    socket.onerror = () => hub.leave(socket, room);
    return response;
  }

  return new Response(PAGE, { headers: { "content-type": "text/html; charset=utf-8" } });
});

And a minimal browser client served as the page:

HTML
<ul id="log"></ul>
<form id="form"><input id="text" autocomplete="off" maxlength="300" /><button>Send</button></form>
<script>
  const params = new URLSearchParams(location.search);
  const room = params.get("room") ?? "general";
  const name = params.get("name") ?? "guest";
  const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/ws?room=${encodeURIComponent(room)}&name=${encodeURIComponent(name)}`);

  const log = document.getElementById("log");
  function add(text) {
    const li = document.createElement("li");
    li.textContent = text;            // textContent, never innerHTML: messages are untrusted
    log.append(li);
  }

  ws.onmessage = (e) => {
    const m = JSON.parse(e.data);
    if (m.type === "history") m.messages.forEach((x) => add(`${x.from}: ${x.text}`));
    else if (m.type === "message") add(`${m.message.from}: ${m.message.text}`);
    else add(`* ${m.text}`);
  };

  document.getElementById("form").onsubmit = (e) => {
    e.preventDefault();
    const input = document.getElementById("text");
    if (input.value.trim()) ws.send(JSON.stringify({ text: input.value }));
    input.value = "";
  };
</script>

The most important line is li.textContent = text. Chat messages are written by strangers; inserting them with innerHTML would let anyone run script in every other user's browser (cross-site scripting).

Several instances: BroadcastChannel

On a platform that runs more than one instance, Ada may be connected to instance 1 and Grace to instance 2. Each hub only has its own sockets, so a message must also reach the other instances. BroadcastChannel delivers a message to every isolate listening on the same channel name (on Deno Deploy, within a region). The pattern: when a message is accepted, publish it; every instance (including the sender) delivers it to its own sockets.

Node.js Two instances linked by BroadcastChannel

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

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

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

A BroadcastChannel does not deliver a message back to the channel object that posted it, which is why accept delivers to local sockets itself. For instances in different regions or machines, replace the channel with a shared mechanism: a message broker (Redis pub/sub, NATS), or KV watch and queues.

Production concerns

  • Authentication: connect with a short-lived token (in a cookie or the first message), not just a name in the URL. Never trust the claimed name.
  • Origin check: refuse sockets from sites you do not own by checking the Origin header before upgrading.
  • Limits: cap sockets per user, message size, and idle time; the hub's rate limiter protects the room, not the process.
  • Cleanup: remove sockets in both onclose and onerror, or memory grows.
  • Moderation: keep message ids so you can delete a message and tell clients to remove it.
  • Observability: log joins, leaves and rejections as structured events.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the hub contain no WebSocket code?

    Business rules in a plain class can be tested with stand-in sockets and reused behind SSE or other transports.
  2. 2. Why should the browser client use textContent instead of innerHTML for messages?

    Untrusted text inserted as HTML enables cross-site scripting. textContent treats it as plain text.
  3. 3. A user connected to instance 1 sends a message. Who receives it without BroadcastChannel?

    A hub holds only the sockets of its own process, so another instance needs a shared channel to learn about the message.
  4. 4. How does the KV key layout produce the 20 newest messages?

    Keys sort by their parts, so putting the timestamp after the room lets a reverse list return the latest entries first.

Summary

  • Keep chat rules (validation, history, rate limits) in a transport-free hub and attach WebSockets as glue code.
  • Store messages under ["chat", room, timestamp, id] and load history with a reverse prefix list.
  • Validate every message, rate-limit per user, sanitize room names and render text safely in the browser.
  • Use BroadcastChannel or another shared channel so several instances see all messages.
  • Plan for authentication, origin checks, limits, cleanup and moderation before going live.

Next: Practice: Exercises and Review