Configure CORS for Separate Frontend and Backend
If the frontend and backend are hosted on different origins, configure Socket.IO CORS appropriately.
For example:
- Frontend: https://chat.example.com
- Backend: https://api.example.com
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.
Do not combine wildcard origins with credentialed browser requests. Configure explicit trusted origins and independently enforce authentication and authorization.
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.
Configure exact frontend origins.
CORS does not authenticate users.
WebSocket origin validation requires separate consideration.