Search code examples
express-sessioni18next

express.js - How to correctly change language with i18next when using express-session?


I preferred not to have language related parameters in the url, so I decided to change the current language using express-session.

After standard configuration of express-session for a proof of concept by reading the documentation (with perhaps misunderstanding) I had an endpoint like:

app.get('myRoute', function(req, res) {
  req.i18n.changeLanguage('en'); // will not load that!!! assert it was preloaded
});

which as you read by the comment (from documentation) "will not load"
Then I came up with this code that worked for me:

router.get('/chz', function(req, res){
 if(req.session){
  req.session.lng = 'zh-TW';
 }
 res.redirect('back');
});

Is there any potential problem with this code (soft of optimization, or security, etc.) and I must somehow use i18n.changeLanguage() to change the language when using express-session? If not, then what is the usage of i18n.changeLanguage()?


Solution

  • Just use the language detector coming with the i18next-express-middleware: https://github.com/i18next/i18next-express-middleware#detector-options

    it already grabs the lng from req.session.lng on every request if enabling that in the order option:

    {
      // order and from where user language should be detected
      order: [/*'path'*/, 'session',  'querystring', 'cookie', 'header'],
      // ...