Handling CORS

Configuration

Since Socket.IO v3, you need to explicitly enable Cross-Origin Resource Sharing (CORS).

  1. const io = require("socket.io")(httpServer, {
  2. cors: {
  3. origin: "https://example.com",
  4. methods: ["GET", "POST"]
  5. }
  6. });

All options will be forwarded to the cors package. The complete list of options can be found here.

Example with cookies (withCredentials) and additional headers:

  1. // server-side
  2. const io = require("socket.io")(httpServer, {
  3. cors: {
  4. origin: "https://example.com",
  5. methods: ["GET", "POST"],
  6. allowedHeaders: ["my-custom-header"],
  7. credentials: true
  8. }
  9. });
  10. // client-side
  11. const io = require("socket.io-client");
  12. const socket = io("https://api.example.com", {
  13. withCredentials: true,
  14. extraHeaders: {
  15. "my-custom-header": "abcd"
  16. }
  17. });

Note: this also applies to localhost if your web application and your server are not served from the same port

  1. const io = require("socket.io")(httpServer, {
  2. cors: {
  3. origin: "http://localhost:8080",
  4. methods: ["GET", "POST"]
  5. }
  6. });
  7. httpServer.listen(3000);

You can disallow all cross-origin requests with the allowRequest option:

  1. const io = require("socket.io")(httpServer, {
  2. allowRequest: (req, callback) => {
  3. const noOriginHeader = req.headers.origin === undefined;
  4. callback(null, noOriginHeader);
  5. }
  6. });

Troubleshooting

  1. Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at xxx/socket.io/?EIO=4&transport=polling&t=NMnp2WI. (Reason: CORS header Access-Control-Allow-Origin missing).

If you have properly configured your server (see above), this could mean that your browser wasn’t able to reach the Socket.IO server.

The following command:

  1. curl "https://api.example.com/socket.io/?EIO=4&transport=polling"

should return something like:

  1. 0{"sid":"Lbo5JLzTotvW3g2LAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}

If that’s not the case, please check that your server is listening and is actually reachable on the given port.