← Back to Blog

Building Real-Time APIs with WebSockets and Node.js

By Stanley Hayford ·

Building Real-Time APIs with WebSockets and Node.js

REST vs WebSockets

REST is request-response. WebSockets provide full-duplex, persistent connections — ideal for chat apps, live dashboards, notifications, and collaborative editing.

Setting Up

import { WebSocketServer, WebSocket } from "ws";
import http from "http";

const server = http.createServer();
const wss = new WebSocketServer({ server });

wss.on("connection", (ws: WebSocket) => {
  console.log("Client connected");

  ws.on("message", (data: Buffer) => {
    const message = JSON.parse(data.toString());
    // Broadcast to all clients
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify(message));
      }
    });
  });

  ws.on("close", () => console.log("Client disconnected"));
});

server.listen(8080);

Authentication

Authenticate during the WebSocket handshake using tokens passed as query parameters or in the protocol header.

Scaling with Redis Pub/Sub

When running multiple server instances, use Redis Pub/Sub to broadcast messages across all nodes. Each server subscribes to a Redis channel and forwards messages to its local WebSocket clients.

Best Practices

  • Implement heartbeat/ping-pong to detect stale connections
  • Use message queuing for guaranteed delivery
  • Handle reconnection logic on the client side
  • Rate limit incoming messages to prevent abuse

Tags: Node.js, WebSocket, Real-Time, API