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
npm install wsconst { 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
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.
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.
More from the lab
CI/CD with GitHub Actions: A Practical Intro
Automate tests, linting and deploys with a single YAML file — never merge broken code again.
PythonTest-Driven Development in Python with pytest
Write the test, watch it fail, make it pass — a hands-on TDD loop with pytest.
DevOpsServerless Functions with AWS Lambda & API Gateway
Run code with no servers to manage — a Lambda behind an API Gateway, gotchas explained.
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 →