Host more than one node server on a single Heroku dyno

During development I often host an express server for frontend and one or more backends in a single node process. They all listen on different ports and communicate over HTTP, keeping the modules completely separated and the interfaces clean.

But that doesn't work on Heroku which gives each dyno just one port. This is fine in production where all those servers will have their own dynos but during development I prefer this single-process configuration as:

a) a single web dyno is free (read: paid by them) on Heroku, a web dyno + one or more workers is not

b) modules usually evolve together and I keep them in the same git repository so I would have to split them much earlier than otherwise, putting each into their own git and their own dyno, making a mess out of development process

I created three virtual routing functions for Connect that allows me to connect as many servers as I like while still listening on a single port. Right now I don't have time to make a real node module out of them so in the meanwhile I've created a gist carrying all three functions:

  1. vroute(route, server) - sends all requests matching the route to the server
  2. vpath(path, server) - sends all requests matching the path to the server but only after removing the path from req.url
  3. vsubdomain(subdomain, server) - sends all requests arriving to the subdomain to the server

So usage would be something like this:

connect()
  // send domain/api reqs to api server without /api
  .use(vpath('api', api)) 
  // send domain/api reqs to api server keeping /api
  .use(vresource('api', api))
  // send api.domain reqs to api server
  .use(vsubdomain('api', api))
  // all other requests will end up here
  .use(frontend)
  .listen(process.env.PORT || 12345);

I'll update this post when I make a module out of these functions.

UPDATE 2014-01-10 09:04: Improved layout

Author

Ivan Erceg

Software shipper, successful technical co-founder, $1M Salesforce Hackathon 2014 winner