Search code examples
node.jsexpressinternationalizationlocale

Node Express i18n maintainable links


Considering i'm using "express", "i18n", "express-session", "cookie-parse", adicionally could use "npm locale" or similar in case need it. Lets say I have routes like this:

"/", "/es/" , "/de/"
"/terms", "/es/terms", "/de/terms"
"/privacy", "/es/privacy", "/de/privacy"
...

How I should set maintainable and automated links that way , if a user have a language like "es" on his cookie or header ... show them links on pages for "es" version of pages AND also consider set a variable with URL so in case I have to update a link , i will only change one time.

One thing I think of was:

set in a i18n file like "es.json"

{ 
  "url_home" : "/es/" ,
  "url_terms" : "/es/terms",
  ...
}

then other files will be like "de.json"

{ 
  "url_home" : "/de/" ,
  "url_terms" : "/de/terms",
  ...
}

I this the right way ? or should I follow any other way recommended ?


Solution

  • I will say now with few testings , best way would be (and i don't suggest using i18n) create a middleware for urls . I have create this like this:

    create a url.json file with:

    {
      "en": {
          "home": "/",
          "terms": "/terms"
      "es": {
          "home": "/es",
          "terms": "/es/terms"
    }
    

    then i used on my methods depending on language in cookie (this is when route is terms (i'm using dot template) locale is my cookie, so in this case:

      const urls = require('urls.json');
    
      ...
    
      app.get('/:lang/terms', function(req, res) {
    
        if (req.params.lang === 'es') {
    
          res.render('terms',{
    
            // get urls for locale cookie language 
            urls: urls[req.locale],
    
          });
        } 
      ...
       //more languages
    });
    

    then in my templates simply:

     <li><a href="{%= it.urls.terms%}">{%=it.__n('help')%}</a></li>