Real-Time Apps with WebSockets in Node.js

Push updates to the browser the instant they happen. Chat, live dashboards and multiplayer — the pattern is the same.

HTTP is request-response; great for pages, bad for "tell me the moment something changes." WebSockets keep a two-way channel open so the server can push at any time — the backbone of chat, live feeds and collaborative apps.

A WebSocket server

bash
npm install ws
javascript
const { WebSocketServer } = require("ws");

const wss = new WebSocketServer({ port: 8080 });

wss.on("connection", (socket) => {
  socket.on("message", (raw) => {
    // broadcast to every connected client
    for (const client of wss.clients) {
      if (client.readyState === 1) client.send(raw);
    }
  });
});

The browser side

javascript
const ws = new WebSocket("ws://localhost:8080");

ws.onopen = () => ws.send(JSON.stringify({ type: "hello", name: "Ada" }));

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  console.log(msg);   // arrived in real time
};

Live dashboard pattern

For dashboards, the server pushes a snapshot whenever the underlying data changes — no polling, no refresh.

javascript
function broadcastState() {
  const payload = JSON.stringify({ type: "state", data: getDashboard() });
  for (const c of wss.clients) if (c.readyState === 1) c.send(payload);
}

// call broadcastState() whenever your data changes:
// a DB trigger, a webhook, a sensor reading...
setInterval(broadcastState, 1000);

Production concerns

  • Reconnect with exponential backoff on the client.
  • Heartbeat / ping to drop dead connections.
  • Authenticate on upgrade (a token in the query or a header).
  • Scale horizontally with a pub/sub broker (Redis) behind the scenes.
If you only need one-way pushes, Server-Sent Events are simpler — but WebSockets remain the right tool for anything bidirectional.

Real-time is a superpower that's now commodity plumbing. This is the same pattern behind the chess platform we built — a move made anywhere is a move seen everywhere.

Your move

Want us to build this for you?

We turn tutorials like these into production systems every day. Tell us what you need.

Start a project →