Express Subdomains Support

Sometimes you just need to host user generated content on their own subdomains. For now express doesn't have a built in support, so here is a simple way to add subdomain support to express.js via simple middleware class (method below true for express v3)

At first you will need an installed express and some server skeleton, something like this:

var express = require('express')
    , http = require('http')
    , app = express()

app.set('port', process.env.PORT || 8080);
app.use(express.logger('dev'));
app.use(app.router);
app.configure('development', function () {
    app.use(express.errorHandler());
});


http.createServer(app).listen(app.get('port'), function () {
    console.log('Express server listening on port ' + app.get('port'));
});

And now we need some middleware to differentiate our subdomains:

module.exports = function (req, res, next) {
    //check if subdomain exists and here is just one
    if (req.subdomains.length != 1) return next()

    var subdomain = req.subdomains[0]
    req.userSubdomain = subdomain
    req.url = '/userSubdomains/' + subdomain + req.url;
    next()
};

Let's place it in some file, e.g. usersSubdomain.js and include it before router in our app.js, and then add some basic routing in our little app:

...
app.use(require('./usersSubdomain'))
app.use(app.router);

app.get('/', function (req, res) {
    res.send('Our project main page')
})
app.get('/blog', function (req, res) {
    res.send('Our project blog')
})
app.get('/userSubdomains/:userSubdomain', function (req, res) {
    res.send('Original url: ' + req.originalUrl + '<br>'
        + 'Replaced url: ' + req.url + '<br>'
        + 'Our user subdomain: ' + req.userSubdomain
    )
})
app.get('/userSubdomains/:userSubdomain/blog', function (req, res) {
    res.send(
        'Here is our humble user "' + req.userSubdomain + '" subdomain blog'
    )
})

Of course it is pretty dumb way to manage subdomains, so you could not as well modify urls at all and just set some req param to differentiate if it is user subdomain or not, in this case your urls management could look like this:

...
app.get('/', notSubDomainCallback, subDomainCallback)

function notSubDomainCallback(req, res, next) {
    if (!req.userSubdomain) return res.send('Our project main page')
    next()
}

function subDomainCallback(req, res, next) {
    res.send('Our user subdomain: ' + req.userSubdomain + ' main page')
}