Course contentsShow
← Node.js
Lesson 1080 of 1,98010. Real-time Communication and WebsocketsFree lesson

Implementing Origin Validation for Security

You will verify connection origins to prevent cross-site websocket hijacking attacks.

In this lesson, you will learn how to secure your WebSocket server by validating the Origin header during the initial handshake to prevent Cross-Site WebSocket Hijacking (CSWSH).

The Risk: Cross-Site WebSocket Hijacking

Unlike standard HTTP requests, the WebSocket handshake is not bound by the Same-Origin Policy. If a user is authenticated in your application, a malicious website can initiate a WebSocket connection to your server from the user's browser. If you don't verify the Origin header, your server might inadvertently authorize that malicious site to communicate on behalf of the user, potentially leaking sensitive data or performing unauthorized actions.

Validating the Origin

During the WebSocket handshake, the browser automatically sends an Origin header indicating where the connection request originated. Your server’s responsibility is to inspect this header and reject the connection if the origin is not on your whitelist.

If you are using the popular ws library, you can perform this check within the verifyClient option of your server constructor:

const WebSocket = require('ws');

const allowedOrigins = ['https://myapp.com', 'https://admin.myapp.com'];

const wss = new WebSocket.Server({
  verifyClient: (info, callback) => {
    const origin = info.origin;

    if (allowedOrigins.includes(origin)) {
      // Allow the connection
      callback(true);
    } else {
      // Reject with 403 Forbidden
      callback(false, 403, 'Forbidden: Origin not allowed');
    }
  }
});

Why This Matters

By explicitly checking the Origin header, you ensure that only your trusted web frontend can establish a full-duplex communication channel with your backend. Even if a user clicks a malicious link, the browser’s request to your WebSocket server will be blocked before the upgrade protocol ever completes.

Always treat the Origin header as untrusted input. While it can be spoofed in non-browser environments (like curl or Postman), browser-based attacks are restricted by the browser's own security model, making this server-side check a vital layer of your defense-in-depth strategy.

Key Takeaway: Always validate the Origin header during the WebSocket handshake to ensure that only trusted, authorized domains can initiate real-time communication sessions with your server.