Philipp
Philipp

Reputation: 1963

How to handle language specific subdomains in express?

Using nodejs and express, I try to set the language based on a "subfolder" in the routes. This language parameter is optional. Is there a way of doing this without having to change all the routes to contain the optional language parameter?

For example, I want mydomain.tld/mypath/ and mydomain.tld/de/mypath/ to trigger the same route for /mypath/ , with a middleware which detects the /de/ (if present) and sets locale variables accordingly.

Upvotes: 0

Views: 571

Answers (1)

dape
dape

Reputation: 162

You will have to resort to checking for the special case of there being a language tag in the route, and then rewriting req.url in the middleware, setting the correct locale variables. Here is a simple sketch example of how this could be done.

var languages = ["de", ...];

function routeLanguage(req, res, next) {
  var lang, parts = req.path.split("/");
  if (parts[1] && (lang = languages[parts[1]])) {
    req.url = req.url.replace(/^\/[^/]*/, "");
    // set locale vars using lang
  }
  return next();
}

This middleware will reroute any "language path" to the normal route (/de/mypath goes to /mypath).

Be careful, as this will not work for the default language if you have a language tag as a path, i.e. /de will route to / with de as language and /de/de will route to /de.

Update:

This simplifies somewhat if you assume a mount point for the middleware, as express can then use it's regex parsing on the path. You could also defer the localization logic to later in the stack, by assigning the parsed language to for example req.lang.

app.use(/^\/(de|en|...)\//, function (req, res, next) {
  req.lang = req.params[0];
  req.url = req.url.replace(/^\/[^/]*/, "");
  next();
});

Upvotes: 1

Related Questions