How to set up local subdomains for Node.js app

jordan picture jordan · Oct 25, 2014 · Viewed 10.5k times · Source

I am running an express app on node.js. The app uses the express-subdomain module to help handle routes for two different subdomains (sub1.example.com and sub2.example.com). I'm hosting the app on AWS Elastic Beanstalk. In my production environment, everything works great. But on my local machine, I cannot get this to work. I tried adding the subdomains to my host file 127.0.0.1 localhost sub1.localhost sub2.localhost. Although that allows me to prepend a subdomain to localhost, the module doesn't recognize this as a valid subdomain, and therefor searches for subdomain routes in my root routes.

In main.js:

var routes = require('./routes/index')(passport);
var sub1_routes = require('./routes/sub1')(passport);
var sub2_routes = require('./routes/sub2')(passport);

app.use(subdomain('sub1', sub1_routes));
app.use(subdomain('sub2', sub1_routes));
app.use('/', routes);

I need to be able to handle this locally. It takes to much time to push a small change to AWS test, iterate, etc.

Answer

bmullan91 picture bmullan91 · Oct 25, 2014

I'm the author of the module :)

For each new subdomain you wish to test locally you must add into your /etc/hosts file. So for example:

localhost is:

127.0.0.1       localhost

a new subdomain would be..

127.0.0.1       sub1.localhost

and another..

127.0.0.1       sub2.localhost

Check out what I have done in the tests.