Need help?

I'm available for remote short term contracting or consultancy work. Please check out my LinkedIn profile for more details on my experience.

Please feel free to use the form below to contact me.

vHosts with Node.JS and Express

This article is going to explain the process of setting up virtual hosts with node.js, using the Express framework. For this to work, you'll need to have node.js and express.js installed.

You can quickly get node setup, by going to their main site - For the most part, all you should have to do is click the install link, and just run the file. 

To get Express installed, it's a bit more work, but nothing too scary. We need to head over to their website - Follow those instructions up until they ask you to create app.js - do NOT use Express to generate an app. This first part is only about creating the vhost 'manager'. All we need in the new directory is whatever npm installed (all the Express stuff), and the app.js file (the vhost manager).

Now that that's all done, we can move on to the actual content of app.js. Copy and paste the following in there.

var express = require('express');
var app = express();

.use(express.vhost('localhost', require('/path/to/website1/app.js').app))
.use(express.vhost('localhost2', require('/path/to/website2/app.js').app))

This will listen on port 3000, and check for specific host names - in this case, localhost and localhost2. If one of those hosts match, it will get an instance of their 'app' to run/use. That's it for the vhost manager.

The next major, but not majorly difficult part, is the actual web apps. Let's use the first vhost, localhost ('/path/to/website1/app.js' ), as an example.

var express = require('express');
var app = = express();

app.get('/', function(req, res){
    res.send('Hello World');

The only major difference here is the addition of '', and the get handler for different requests. Lets start with the exports keyword. It gives the require function access to any value or object that is set under it. In this example, it will have access to 'app', because is set. Looking back on the vhosts manager, you'll notice that it references .app after the require.

That's about as simple as it gets for vhost management. If you have any questions, or spot any mistakes, please leave a comment.

jon | June 23, 2013 | Comments (1)


this is nice article. thanks
i will try to vHosts with Node.JS
Comment by sultan - December 01, 2014 @ 5:59 am

Name (required)
Email (will not be published) (required)