Introduction to WebSockets

By

Published · Updated

Tagged: Networking

Learn WebSockets and real-time web patterns: when to pick polling, SSE, or WebSockets, Node.js ws servers, jittered reconnect backoff, backpressure, and debugging.

WebSockets are an alternative to HTTP communication in Web Applications.

They offer a long lived, bidirectional communication channel between client and server.

Once established, the channel is kept open, offering a very fast connection with low latency and overhead.

WebSocket vs SSE vs Polling

Six questions to pick WebSocket, SSE, or HTTP polling — with a comparison table and anti-recommendations for serverless.

WebSocket vs SSE vs pollingInteractive · runs in your browser

Browser support for WebSockets

WebSockets are supported by all modern browsers.

How WebSockets differ from HTTP

HTTP is a very different protocol, and also a different way of communicate.

HTTP is a request/response protocol: the server returns some data when the client requests it.

With WebSockets:

WebSockets are great for real-time and long-lived communications.

HTTP is great for occasional data exchange and interactions initiated by the client.

HTTP is much simpler to implement, while WebSockets require a bit more overhead.

Secured WebSockets

Always use the secure, encrypted protocol for WebSockets, wss://.

ws:// refers to the unsafe WebSockets version (the http:// of WebSockets), and should be avoided for obvious reasons.

Create a new WebSockets connection

const url = 'wss://myserver.com/something'
const connection = new WebSocket(url)

connection is a WebSocket object.

When the connection is successfully established, the open event is fired.

Listen for it by assigning a callback function to the onopen property of the connection object:

connection.onopen = () => {
  //...
}

If there’s any error, the onerror function callback is fired:

connection.onerror = (error) => {
  console.log(`WebSocket error: ${error}`)
}

Sending data to the server using WebSockets

Once the connection is open, you can send data to the server.

You can do so conveniently inside the onopen callback function:

connection.onopen = () => {
  connection.send('hey')
}

Receiving data from the server using WebSockets

Listen with a callback function on onmessage, which is called when the message event is received:

connection.onmessage = (e) => {
  console.log(e.data)
}

Implement a server in Node.js

ws is a popular WebSockets library for Node.js.

We’ll use it to build a WebSockets server. It can also be used to implement a client, and use WebSockets to communicate between two backend services.

Install it using npm. This example uses ws 8:

npm init
npm install ws@8

The code you need to write is very little. Since ws 8 the server class is exported as WebSocketServer. The older new WebSocket.Server(...) form you’ll find in old tutorials still works as an alias, but the named export is the one the library documents today:

const { WebSocketServer } = require('ws')

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

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    console.log(`Received message => ${message}`)
  })
  ws.send('ho!')
})

This code creates a new server on port 8080 (the default port for WebSockets), and adds a callback function when a connection is established, sending ho! to the client, and logging the messages it receives.

Try it locally

I used to link two Glitch projects here, a server and a client, but Glitch shut down its app hosting in 2025 and they are gone. You don’t need them anyway, everything runs on your machine in a minute.

Save the server code above as server.js and start it:

node server.js

Then take the client code from the beginning of this post, point it at ws://localhost:8080 instead of the wss:// URL (we’re on localhost, so no TLS here), and paste it into the browser console. You’ll see ho! printed, and the terminal running the server will print Received message => hey.

The same client code also runs in Node.js with no changes, because since Node.js 22 the WebSocket class is available globally, exactly like in the browser. Save it as client.js and run node client.js in a second terminal while the server is up.

Debugging websockets

Chrome and Firefox have a handy way to visualize all the information that is sent through WebSockets. Their DevTools support is always improving. Firefox at the time of writing has the most useful and informative debugging tool.

In both, you look into the Network panel and choose WS to filter only WebSockets connections. Click the connection to see the handshake headers and the list of messages sent and received. With the example above you’ll see hey going out and ho! coming in.

The Firefox DevTools can do much more than that. In the example I used to test, I’m just sending a string, but if you send JSON or Socket.IO data Firefox parses it and shows it as a tree you can expand, so you can inspect any data that’s sent in a more organized fashion.

Check out this post on Mozilla Hacks to know more about how to use this tool.

Choose between polling, SSE, and WebSockets

I do not reach for WebSockets first. Pick the simplest real-time transport that fits your traffic:

TransportBest forTradeoff
HTTP pollingDashboards and status checks every 10–60sSimplest to scale; adds latency between polls
Server-Sent Events (SSE)Server-to-browser streams (AI tokens, notifications, live feeds)Plain HTTP, automatic browser reconnect; one-way only
WebSocketsFast two-way traffic (chat, multiplayer, collaborative editing)Lowest latency; you manage reconnects, heartbeats, and backpressure

Reconnect with jittered backoff

Unlike EventSource, WebSockets do not reconnect on their own. When a server restarts, thousands of tabs reconnecting on the same second will knock it right back down.

Spread retries with capped exponential backoff plus random jitter, and show the user honestly when data is stale:

let attempt = 0

function scheduleReconnect(connect) {
  attempt += 1
  const base = Math.min(30_000, 1000 * 2 ** attempt)
  const jitter = Math.random() * 500
  setTimeout(connect, base + jitter)
}

Reset attempt = 0 once a connection stays open cleanly, and fetch a fresh HTTP snapshot after reconnecting so you never miss updates that happened while offline.

Protect your server with backpressure

A slow browser tab can fall behind a bursty server. If you keep calling ws.send() blindly, outbound buffers grow until Node runs out of memory.

Check ws.bufferedAmount before sending, coalesce noisy counters (like live viewer counts), and disconnect a consumer that cannot keep up so it recovers through a clean HTTP snapshot:

const MAX_BUFFERED = 512 * 1024

function safeSend(ws, frame) {
  if (ws.bufferedAmount > MAX_BUFFERED) {
    ws.close(4429, 'slow consumer')
    return false
  }
  ws.send(frame)
  return true
}

Always authenticate the WebSocket upgrade request on the server (using your session cookie or short-lived token) and validate every incoming message shape just like a regular HTTP endpoint.

Want me to talk about your product? You can sponsor this site.

Related posts about network: