32

Is it possible to use Socket.IO in a cross domain manner? If so, how? The possibility is mentioned around the web but no code examples are given anywhere.

0

8 Answers 8

28

Quoting the socket.io FAQ:

Does Socket.IO support cross-domain connections?

Absolutely, on every browser!

As to how it does it: Native WebSockets are cross-domain by design, socket.io serves a flash policy file for cross-domain flash communication, XHR2 can use CORS, and finally you can always use JSONP.

2
  • 3
    I'm actually running into some issues with Cross Domain socket.io connections. When socket.io reverts to XHR-Polling/Ajax, socket.io attempts to make requests to the current domain /socket.io/1, this causes a cannot 'onClose' on null. Googling this error brings up a couple github issues, but nothing that applies to my situation (as I think it's a config problem, not a bug). Commented Feb 7, 2013 at 3:13
  • 3
    This answer is way, way out of date. Browsers implement same-origin protections on webSockets just like they do for Ajax calls. If you want a cross origin socket.io connection to be allowed, you have to explicitly enable in your socket.io server.
    – jfriend00
    Commented Apr 28, 2015 at 1:15
25

**Socket.IO version --> 1.3.7 **

Is it possible to use Socket.Io in a cross domain manner? Yes, absolutely.

If so, how?

Option 1: Force use of Websockets only

By default, websockets are cross domain. If you force Socket.io to only use that as means to connect client and server, you are good to go.

Server side

//HTTP Server 
var server = require('http').createServer(app).listen(8888);
var io = require('socket.io').listen(server);

//Allow Cross Domain Requests
io.set('transports', [ 'websocket' ]);

Client side

var connectionOptions =  {
            "force new connection" : true,
            "reconnectionAttempts": "Infinity", //avoid having user reconnect manually in order to prevent dead clients after a server restart
            "timeout" : 10000, //before connect_error and connect_timeout are emitted.
            "transports" : ["websocket"]
        };

 var socket = io("ur-node-server-domain", connectionOptions);

That's it. Problem? Won't work on browsers (for clients) who don't support websockets. With this you pretty much kill the magic that is Socket.io, since it gradually starts off with long polling to later upgrade to websockets (if client supports it.)

If you are 100% sure all your clients will access with HTML5 compliant browsers, then you are good to go.

Option 2: Allow CORS on server side, let Socket.io handle whether to use websockets or long polling.

For this case, you only need to adjust server side setup. The client connection is same as always.

Server side

//HTTP Server 
var express=require('express');
//Express instance
var app = express();

//ENABLE CORS
app.all('/', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
 });

That's it. Hope it helps anyone else.

0
17

Simply insert your remote domain name when creating the client side socket:

const socket = new WebSocket('ws://example.com/echo');

Some documentation on MDN

You should however ensure that your server accepts websockets (configuration and headers).


Old version :

var socket = io.connect('http://example.com:8080');
3
  • Too old answer. io.connect is not a function.
    – Saras Arya
    Commented Aug 4, 2016 at 12:44
  • 1
    io.connect should still be working (2016): socket.io/docs/#using-with-express-3/4. Also see socket.io/docs/client-api/: "connect Fired upon a successful connection."
    – vinyll
    Commented Aug 6, 2016 at 22:46
  • @Chayemor is that possible to emit the events with using particular room at cross domain ? io.to(socket.id).emit("sendData", data)
    – maranR
    Commented Oct 11, 2022 at 13:59
8

Socket.io supports cross-domain connections, but keep in mind that your cookie will not be passed to the server. You'll have to either:

(1) come up with an alternate identification scheme (a custom token or a javascript cookie-- just keep in mind this should not be the actually session id, unless you want to put yourself at risk of session hijacking)

or (2) send a good old fashioned HTTP JSONP request to the server first to get the cookie. Then it will be transmitted w/ the socket connection handshake.

1
  • Stuck at the exact problem, I cannot be able to pass cookies to server. What is the best practice to achieve this in angular
    – VinoPravin
    Commented Apr 15, 2020 at 12:55
3

create your server by io like this:

const server = require('http').createServer();

const io = require('socket.io')(server, {
    origins:["127.0.0.1:8000"],
    path: '/',
    serveClient: false,
    // below are engine.IO options
    pingInterval: 20000,
    pingTimeout: 5000,
    cookie: false
});

io.on('connection', function(socket){
    console.log("here new user welcom")
});


server.listen(3000,function(){
    console.log('listening on *:3000')});

in the origins array specify valid origin

1
2

Easy and security!

In the main file place it before io.on('connection'), add the lines:

io.set('origins', 'yoursite.com:*');

io.on('connection', function (socket) {
1

Yes it does. I have implemented cross domain socket.io to test whether it works.

<script src="http://your-nodejs-domain.com:3000/public/js/jquery.js"></script>
  <script src="http://your-nodejs-domain.com:3000/socket.io/socket.io.js"></script>
  <script>

      var socket = io.connect('http://your-nodejs-domain:3000');
      $(document).ready(function(){

          socket.on('test message', function(msg){
               console.log("Got the message: " + msg);
          });
      });

  </script>

That should work fine.

1
  • could you give the complete code of the server.js app
    – zero8
    Commented Dec 4, 2017 at 13:30
1

As of v4, according to the docs:

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

You can use the cors key in the configuration object passed to new Server(). See this basic example from the above docs page:

import { createServer } from "http";
import { Server } from "socket.io";

const httpServer = createServer();
const io = new Server(httpServer, {
  cors: {
    origin: "https://example.com"
  }
});

origin can be an array to accept multiple origins.

Other options include allowRequest, allowedHeaders, withCredentials, extraHeaders and others from the cors package which ultimately handles the CORS headers under the hood.

I also tested slightly different syntax than this answer, which worked for me with 4.4.1:

const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server, {
  cors: {origin: ["https://glitch.me", "https://cdpn.io"]}
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.