and nginx workaround

If you are running a node.js app, it is a good idea to use a reverse proxy (nginx, HAproxy) along side of it.  The main reason being that you aren’t wasting precious cycles on your single threaded node.js server by making it serve static content (javascript, images, css, etc).  nginx and node.js work great together.  Unfortunately, most node.js apps rely on websockets, which are a new HTML5 standard that allows full duplex communication between client and server.  I say “unfortunately” because most reverse proxies do not support websockets inherently.  So if you aren’t a sys admin or server guy, adding, compiling and configuring a reverse proxy module isn’t trivial.  The good news: there is a pure javascript workaround.

Ideally, a sample workflow would look like this:

  1. nginx listens on port 80
  2. nodejs listens on port 8080
  3. listens on port 8080 through nodejs app
  4. nginx proxies any requests on port 80 over to nodejs on 8080
  5. client connects directly to node/socket server on port 8080 and communicates directly without involvement of a reverse proxy

Following is the gist I wrote of the code to do it: