gial gial - 5 months ago 30
Node.js Question

How to get optional language parameter from URL in Express routes?

I'm stuck with a stupid problem:
How to work with optional locale parameter?

That's what I mean:

For example, I have frontpage and contacts, here is routes:

app.get('/', frontpage.get);
app.get('/contacts', contacts.get);

Now I'm trying to add localization to my site

app.all('/:lang?*', language.all); -> detect and set locale
app.get('/:lang?', frontpage.get);
app.get('/:lang?/contacts', contacts.get);

The only problem is when I don't use lang-parameter in URL:

because Express uses 'contacts' as a language parameter.
(+ I don't like this copy-pasted

I think, I just took the wrong way.

How to use locale parameter from URL in Express?

PS: I dont want to use subdomains
or querystring
. I want exactly this variant


Most modules use Accept-Language so I can't find any that use the path like this that you might be able to use. So you'll need to define your own middleware that initializes before everything else. Express's Router doesn't really help for your usecase.

app.use(function(req, res, next){
    var match = req.url.match(/^\/([A-Z]{2})([\/\?].*)?$/i);
    if (match){
        req.lang = match[1];
        req.url = match[2] || '/';

Now you can use req.lang in your routes or other middleware to configure your translation logic and since we have rewritten the URL, later logic will not know that there is a language param.