Subdomain routing (Express)

It would be great if the routing for nodejs projects could take into account the subdomain.

So a route for / could be treated differently depending if the entry point is domain.com/ or sub.domain.com/

I believe Express provides this info in req.subdomains

req.subdomains

An array of subdomains in the domain name of the request.

// Host: "tobi.ferrets.example.com"
console.dir(req.subdomains)
// => ['ferrets', 'tobi']

There is also a middleware for this for inspiration or usage:

From a UI perspective I think with a new field in the route where you can enter the subdomain if any would be enough. And when viewing the list of routes a tag next to the route with the subdomain string.

Use cases(among others):

  • Separate Marketing site from Webapp site ( www.website.com and app.website.com)
  • Different entry points depending on type of users (user.website.com and client.website.com)
  • API subdomain (api.myapp.com)
  • SAAS multi-tenancy

Actually I just saw brand new code for “custom SC routes”. Related?

Yes you will be able to do full custom routing and middleware in NodeJS.

Not sure about the subdomain routing maybe @patrick can answer

1 Like

I gave it a few tries with the middleware and was able to handle simple redirects and static when requests came from the subdomain while forwarding everything to Wappler’s router when not from the subdomain. That was pretty easy.

A completely different topic was when trying to deal with SC and templateView routes from the subdomain. It was a nightmare of never ending loops :smiley:

We need @patrick indeed.

Do a simple url rewrite of the url in your custom middleware. Following will prefix all urls accessed from the api subdomain with api/.

exports.handler = function(app) {
  app.use((req, res, next) => {
    if (req.subdomains[0] == 'api') {
      req.url = '/api' + req.url;
    }
    next();
  });
}
2 Likes

Mindnote: Do not code pass midnight.

Thanks @patrick! That was easy. I was overcomplicating everything.
I need to to do a few adjustments for my static assets(JS,CSS and translation files) that are loaded from routes.route.data info but this points me in the right direction.