how to set socket.io origins to restrict connections to one url

If you dig into Socket.io source code, you will find such lines:

var origin = request.headers.origin || request.headers.referer
  , origins = this.get('origins');

...

var parts = url.parse(origin);
parts.port = parts.port || 80;
var ok =
  ~origins.indexOf(parts.hostname + ':' + parts.port) ||
  ~origins.indexOf(parts.hostname + ':*') ||
  ~origins.indexOf('*:' + parts.port);

As you can see Socket.io takes origin (or referer) that came from the client, retrieves domain name and port,
and compares with the origins option you specified.

So the valid origins values are (* means “any”):

  • testsite.com:80
  • http://testsite.com:80
  • http://*:8080
  • *:8080
  • testsite.com:* http://someotherdomain.com:8080 (multiple origins separated by space)
  • testsite.com:*/somepath (socket.io will ignore /somepath)
  • *:*

And these are invalid (because no port number):

  • testsite.com
  • http://testsite.com
  • http://testsite.com/somepath

Also note that if you specify sub.testsite.com as origins value, the testsite.com will be valid origin.

Leave a Comment