Node.js theorytheory 0/50 · 0%
Web3 integration · medium

31. WebSockets for live data

Subscribing to new blocks, pending transactions and logs.

Unlike request/response HTTP, a WebSocket keeps one connection open in both directions, letting a node push events as they happen — new blocks, pending transactions, contract event logs — instead of the client polling.

js
import WebSocket from "ws";

const ws = new WebSocket(process.env.WS_RPC_URL);

ws.on("open", () => {
  ws.send(JSON.stringify({
    jsonrpc: "2.0", id: 1, method: "eth_subscribe", params: ["newHeads"],
  }));
});

ws.on("message", (data) => {
  const msg = JSON.parse(data.toString());
  if (msg.method === "eth_subscription") {
    console.log("new block:", msg.params.result.number);
  }
});

WebSocket connections need reconnection logic: networks drop, nodes restart, and a production service must detect a closed socket and re-subscribe rather than silently going quiet.

Check your understanding

  1. 1. What is the main advantage of a WebSocket over HTTP polling for blockchain events?

  2. 2. What must a production WebSocket client handle that a simple example often skips?

  3. 3. What RPC method subscribes to new block headers?