Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 36 ยท Testing and Deployment

Security Hardening for Socket.IO

Harden a Socket.IO server: CORS and origin checks, authentication at the handshake, payload validation, per-socket rate limiting, size limits and safe output.

A WebSocket server is a long-lived door into your application, open to anyone who can reach it. Every event handler is a public API endpoint: it can be called with any arguments, in any order, as often as an attacker likes. Hardening means making each of those assumptions explicit: who may connect, from where, how often, how large, and what the data may contain.

Socket.IO is not available in the runner on this site, so server configuration is shown read-only. The runnable examples implement the core defenses (origin check, validation, token bucket) as plain Node.js functions you can reuse inside real handlers.

Threats in one picture

What can go wrong

Impersonation Connecting as someone else without checking identity.
Cross-site abuse A hostile web page opens a socket as the logged-in user.
Malformed input Wrong types, huge payloads, unexpected fields.
Floods Thousands of events per second from one client.

Each one has a defense in the next sections.

1 / 2

1. Allow only your origins (CORS and CSRF)

Browsers enforce CORS on the polling transport, but WebSocket connections are not covered by CORS: any page can open a WebSocket to your server, and the browser will attach the user's cookies. That is cross-site WebSocket hijacking. Defend with an explicit origin allow-list:

JavaScript
const ALLOWED = ["https://app.example.com", "https://admin.example.com"];

const io = new Server(httpServer, {
  cors: {
    origin: ALLOWED,       // never "*" with credentials
    credentials: true,
  },
  allowRequest: (req, callback) => {
    const origin = req.headers.origin;
    // non-browser clients send no Origin header; decide whether to accept them
    callback(null, origin === undefined || ALLOWED.includes(origin));
  },
});

cors.origin only controls the CORS response headers. allowRequest actually rejects the connection, for both polling and WebSocket. Use both. If you authenticate with a token in the handshake auth object instead of cookies, hijacking is much harder, because a hostile page cannot read the token.

Node.js Origin allow-list check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Match origins exactly. Checks like origin.includes("example.com") or endsWith are classic bypasses.

2. Authenticate at the handshake

Check identity once, before the connection exists, in a middleware, and reject with an error. Do not let anonymous sockets connect and then check inside each handler:

JavaScript
io.use(async (socket, next) => {
  try {
    const token = socket.handshake.auth?.token;
    if (typeof token !== "string") throw new Error("missing token");
    const user = await verifyJwt(token);           // checks signature, expiry, audience
    socket.data.userId = user.id;
    socket.data.role = user.role;
    next();
  } catch {
    next(new Error("unauthorized"));               // client gets connect_error with this message
  }
});

Then authorize each action: being connected is not the same as being allowed to do something. join should check membership, and admin events should check socket.data.role. Never accept a user id or role from the event payload when the server knows it. Do not put tokens in the URL query string, since URLs end up in logs.

3. Validate every payload

Event arguments are untrusted input, exactly like a JSON request body. Check type, shape, length and range, and reject extra fields:

JavaScript
socket.on("message:send", (payload, ack) => {
  const result = parseMessage(payload);
  if (!result.ok) return ack?.({ status: "error", message: result.error });
  // use result.value only
});

Also guard against a missing or non-function ack: ack?.() is not enough if a client sends a string as the ack. Use typeof ack === "function".

Node.js A strict payload validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Schema libraries (zod, valibot, ajv) do the same job with less code. Whichever you use, apply it to every event, including ones you think only your own client emits.

4. Rate limit per socket

A client can send events as fast as it can. Add a limiter per connection. A token bucket allows short bursts and a steady average rate:

JavaScript
io.on("connection", (socket) => {
  const bucket = createBucket({ capacity: 10, refillPerSec: 5 });
  socket.use(([event], next) => {            // runs for every incoming event of this socket
    if (!bucket.take()) return next(new Error("rate limited"));
    next();
  });
  socket.on("error", (err) => socket.emit("error:rate", err.message)); // errors from socket.use arrive here
});

Limit connections too: per IP (carefully, because of NAT) and per user, at the proxy or in the handshake middleware. Disconnect clients that keep violating limits.

Node.js Token bucket with a fake clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

5. Limit sizes and time

  • maxHttpBufferSize (default 1 MB) caps a single message; lower it if you never need big payloads.
  • pingTimeout and connectTimeout (default 45 s for the namespace connect) stop half-open handshakes from piling up.
  • Cap rooms per socket and members per room if users create them.
  • Cap per-user connection count: a user with 500 tabs is a bug or an attack.
JavaScript
const io = new Server(httpServer, {
  maxHttpBufferSize: 1e5,   // 100 KB
  connectTimeout: 10000,
  pingTimeout: 20000,
});

6. Handle output safely

  • Escape on render. Messages from other users are untrusted. In the browser, use textContent or your framework's escaping, never innerHTML. A chat that does li.innerHTML = msg.text is an XSS hole that spreads to every room member.
  • Do not broadcast sensitive fields. Build the outgoing object explicitly ({ id, name, text }), do not emit database rows.
  • Authorize rooms. A room name from a client is just a string; socket.join(room) with no check lets anyone listen to admin or another user's private room.

7. Operational hygiene

  • Use TLS (wss) everywhere; mixed content is blocked and plaintext leaks tokens.
  • Keep dependencies updated: ws, engine.io and socket.io have had denial-of-service fixes, so apply patch releases.
  • Do not log tokens, passwords or message bodies.
  • Do not run the Admin UI without authentication (monitoring).
  • Tell clients nothing about internals: error messages like "unauthorized" are enough.
  • Rotate secrets and make tokens short-lived; refresh them with the function form of auth on reconnect.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is cors.origin alone not enough to stop a hostile page from opening a WebSocket?

    Browsers do not apply CORS to WebSocket, and cookies are attached, so reject unknown origins with allowRequest.
  2. 2. Where should authentication normally happen?

    Rejecting at the handshake means anonymous sockets never exist, and handlers can rely on socket.data being set.
  3. 3. What is the advantage of a token bucket over a fixed counter per second?

    Tokens accumulate up to a capacity, so normal bursts pass while sustained floods get blocked.
  4. 4. How should a client-supplied room name be treated?

    Joining arbitrary rooms lets users eavesdrop on others, so authorize membership on the server.

Summary

  • Allow-list origins with allowRequest; WebSocket is not protected by CORS.
  • Authenticate in handshake middleware, then authorize every action.
  • Validate each payload with a whitelist, and never trust client-sent identity or roles.
  • Rate-limit per socket (token bucket), cap sizes and connection counts.
  • Escape output, build outgoing objects explicitly and keep dependencies and secrets fresh.

Next: Project: A Chat Room