Getting socket.io to Work in the Wild

I created a fairly straight-forward node application with socket.io, but when I put it into production, I couldn’t get it to work. It was dead on arrival. After looking up a ton of examples I figured out what the problem was. (I apologize in advance if this is obvious to seasoned node developers.) Assuming everything else is running…

Server-side

If you have something that looks like this, you need to make sure you pass the "0.0.0.0" second argument to app.listen().

var app = express()
var server = app.listen( 3000, "0.0.0.0" )  // <-- "0.0.0.0"
var router = express.Router()
var io = require("socket.io").listen( server )

This informs your code that you’re no longer working on localhost/127.0.0.1.

Client-side

The next thing you need to do is find the following line in your controller,

var socket = io.connect( "http://localhost" )

And change it to,

var socket = io.connect( window.location.origin )

Assuming everything else was working the way you expected it to in development, this should get you up and running in your production environment.