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

Designing for Cross-Origin Resource Sharing

You will configure strict CORS policies to permit WebSocket connections from trusted domain origins only.

In this lesson, you will learn how to secure your WebSocket handshake by enforcing strict Cross-Origin Resource Sharing (CORS) policies to ensure only trusted domains can establish a connection.

The WebSocket Handshake Security Gap

While many developers associate CORS primarily with standard HTTP requests, the WebSocket protocol (ws:// or wss://) begins with an HTTP GET request known as the "handshake." If you do not explicitly validate the Origin header during this initial phase, any website on the internet can attempt to initiate a socket connection to your server, potentially exposing your real-time services to Cross-Site WebSocket Hijacking (CSWSH) attacks.

Configuring Origin Validation

When using common libraries like socket.io or the native ws module, you should never default to an "allow-all" policy (often represented by *). Instead, define a whitelist of trusted domains. By intercepting the handshake request, you can inspect the origin header and reject connections that do not originate from your verified frontend deployments.

Here is how you might configure this with a standard WebSocket server setup:

const WebSocket = require('ws');
const wss = new WebSocket.Server({
  noServer: true,
  verifyClient: (info, callback) => {
    const trustedOrigins = ['https://app.myapp.com', 'https://admin.myapp.com'];
    const origin = info.origin;

    if (trustedOrigins.includes(origin)) {
      callback(true); // Permit the connection
    } else {
      callback(false, 403, 'Forbidden: Origin not trusted');
    }
  }
});

Why Strict Policies Matter

By validating the Origin header, you ensure that the browser executing your client-side JavaScript is the only one authorized to interact with your server’s real-time events. Even if a malicious site attempts to perform actions on behalf of your users, your server will detect the mismatched domain during the handshake and immediately terminate the connection before a persistent socket is ever established. This approach effectively keeps your real-time infrastructure isolated from external malicious scripts.

Key Takeaway: Always implement an explicit origin whitelist in your WebSocket handshake logic to prevent unauthorized cross-origin connections and protect your real-time services from hijacking.