Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express get sub-domain name

is there a way to use the express router to get the variable of the subdomain.

Lets say I have foo.example.com how can I get an output of foo.

Thanks

like image 698
Corentin Caer Avatar asked Sep 27 '16 17:09

Corentin Caer


2 Answers

In Express 4.x you can use req.subdomains property.

// Host: "tobi.ferrets.example.com"
req.subdomains
// => ["ferrets", "tobi"]

ref.: https://expressjs.com/en/4x/api.html#req.subdomains

like image 153
danilopopeye Avatar answered Sep 22 '22 21:09

danilopopeye


Express 4.x comes req.subdomains but if you are using older version or want to play your own code then can be used other framework as well then you may like

var app = express();

app.use(function(req, res, next) {
    var host = req.get('host');
    console.log(getSubdomain(host));
    console.log(getSubdomainList(host));
    next();
})

function getSubdomain(host) {
    var subdomain = host ? host.substring(0, host.lastIndexOf('.')) : null;
    return subdomain;
}

function getSubdomainList(host) {
    var subdomainList = host ? host.split('.') : null;
    if(subdomainList)
        subdomainList.splice(-1, 1);
    return subdomainList;
}
like image 27
Arif Khan Avatar answered Sep 19 '22 21:09

Arif Khan