Configure CORS for Separate Frontend and Backend

If the frontend and backend are hosted on different origins, configure Socket.IO CORS appropriately.

For example:

Configure the exact frontend origin.

Remember that CORS primarily governs browser access to HTTP long-polling requests. It is not a replacement for authentication or authorization, and WebSocket origin validation should also be considered.

Avoid Wildcard Origins with Credentials

Do not combine wildcard origins with credentialed browser requests. Configure explicit trusted origins and independently enforce authentication and authorization.

Configure Socket.IO CORS
const io = new Server(httpServer, {
  cors: {
    origin: ['https://chat.example.com'],
    methods: ['GET', 'POST'],
    credentials: true
  },
  allowRequest: (request, callback) => {
    const origin = request.headers.origin;
    const allowedOrigins = ['https://chat.example.com'];

    callback(null, allowedOrigins.includes(origin));
  }
});

Allows the specified browser origin and applies an origin check during the Engine.IO handshake. The allowRequest callback is an additional origin restriction, not a substitute for authentication.

Key Takeaways
  • Configure exact frontend origins.

  • CORS does not authenticate users.

  • WebSocket origin validation requires separate consideration.