express-subdomain handling any subdomain

1k views Asked by At

I'm trying to use https://github.com/bmullan91/express-subdomain for subdomain routing in express. The following are the contents of my main.js and src/routes/site files.

const express = require('express');
const bodyParser = require('body-parser');
const subdomain = require('express-subdomain');

const siteRouter = require('./src/routes/site');

const app = express()

app.use(express.json() );
app.use(express.urlencoded());
app.use(express.static('public'));
app.use(subdomain('*.www', siteRouter));

app.get('/', function(req, res) {
    res.send('Homepage');
});

const server = app.listen(80,'x3.loc', function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('X3 listening at http://%s:%s', host, port);
});


const express = require('express');

let router = express.Router();

router.get('/', function(req, res) {
    res.send('Welcome to site');
});

module.exports = router;

This way of doing app.use(subdomain('*.www', siteRouter)); has been suggested in https://github.com/bmullan91/express-subdomain/issues/33 but does not work.

I have also tried just * as the subdomain aswell, but that caused the homepage w/o a subdomain, to get treated like one aswell. How could I get this to work?

1

There are 1 answers

0
Vasan On BEST ANSWER

We know that / matches any base path regardless of subdomain. So I made your homepage middleware "subdomain-aware" like so:

app.get('/', function(req, res,next) {
    /* If there are any subdomains, skip to next handler, since request is not for the main home page */
    if (req.subdomains.length > 0) {
        return next();
    }
    res.send('Homepage');
});

Then I placed the middleware for subdomains below the homepage middleware like so:

app.use(subdomain('*', siteRouter));

This makes homepage middleware to serve requests for x3.loc and the subdomain middleware to serve requests for any subdomain like api.x3.loc or api.v1.x3.loc.

But in my opinion, the real fix should be done in the module. I think it should be changed so that either the case where req.subdomains being empty is handled, or * is matched against an actual string, instead of skipping the iteration.

I am surprised that the fix suggested in bug 33 worked as-is for the reporter. In my testing, it works the opposite way i.e. www.example.com goes to subdomain middleware while stat1.example.com goes to the homepage middleware. Perhaps the reporter saw this and swapped the middleware bodies.