Handling CORS

Configuration

As of Socket.IO v2, the server will automatically add the necessary headers in order to support Cross-Origin Resource Sharing (CORS)

The origins option should be used to provide a list of authorized domains:

  1. const io = require("socket.io")(httpServer, {
  2. origins: ["https://example.com"]
  3. });

Please note that by default, ALL domains are authorized. You should explicitly allow/disallow cross-origin requests in order to keep your application secure:

  • without CORS (server and client are served from the same domain):
  1. const io = require("socket.io")(httpServer, {
  2. allowRequest: (req, callback) => {
  3. callback(null, req.headers.origin === undefined); // cross-origin requests will not be allowed
  4. }
  5. });
  • with CORS (server and client are served from distinct domains):
  1. io.origins(["http://localhost:3000"]); // for local development
  2. io.origins(["https://example.com"]);

The handlePreflightRequest option can be used to customize the Access-Control-Allow-xxx headers sent in response to the preflight request.

Example with cookies (withCredentials) and additional headers:

  1. // server-side
  2. const io = require("socket.io")(httpServer, {
  3. origins: ["https://example.com"],
  4. handlePreflightRequest: (req, res) => {
  5. res.writeHead(200, {
  6. "Access-Control-Allow-Origin": "https://example.com",
  7. "Access-Control-Allow-Methods": "GET,POST",
  8. "Access-Control-Allow-Headers": "my-custom-header",
  9. "Access-Control-Allow-Credentials": true
  10. });
  11. res.end();
  12. }
  13. });
  14. // client-side
  15. const io = require("socket.io-client");
  16. const socket = io("https://api.example.com", {
  17. withCredentials: true,
  18. transportOptions: {
  19. polling: {
  20. extraHeaders: {
  21. "my-custom-header": "abcd"
  22. }
  23. }
  24. }
  25. });

Troubleshooting

  1. Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at xxx/socket.io/?EIO=3&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=3&transport=polling"

should return something like:

  1. 96: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.