Host-based tenant routing
A middleware or route needs to identify the tenant or region encoded in a request hostname.
Express.js · Pipe
req.subdomains returns the request hostname’s subdomain labels as a string array. Express uses the configurable subdomain offset, defaulting to 2, to determine where those labels begin.
req.subdomains provides the request host's subdomain labels as an array. Express uses the subdomain offset setting, which defaults to 2, to decide which rightmost labels belong to the registered domain rather than the subdomain list.
req.subdomainsString[]: an array of subdomains in the request domain name.
tobi.ferrets.example.com as the request host.subdomain offset; the default assumes two rightmost hostname segments are the domain portion.const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.json({ subdomains: req.subdomains });
});
app.listen(3000);For a host such as tobi.ferrets.example.com, request handling returns the detected subdomain labels in req.subdomains.
A middleware or route needs to identify the tenant or region encoded in a request hostname.
Application logic must expose hostname-derived labels to a response or downstream service.
An application uses a domain suffix structure that differs from Express’s default assumption.
req.subdomains return?req.subdomains is a String[] containing the request hostname’s subdomain labels. For tobi.ferrets.example.com, Express returns ['ferrets', 'tobi'].
Follow-up: How would you change which labels Express treats as subdomains? Set the application’s subdomain offset with app.set to match the domain structure.
Express determines the starting point for subdomain segments using the application’s subdomain offset. That setting defaults to 2, so the two rightmost hostname segments are excluded from the returned subdomain array.
Follow-up: Why might the default be unsuitable? Hosted domains with a different effective suffix structure may require a custom offset.
The property is read from the request object and has the documented type String[]. Its values are ordered from the nearest subdomain to the farthest subdomain in the documented example.
Follow-up: What configuration API changes the calculation? Use app.set for the subdomain offset application setting.
req.hostnamereq.hostapp.setsubdomain offset