i18next/i18next-http-middleware

Is i18n of each request isolated?

oney opened this issue · 3 comments

oney commented

Suppose my codes are

app.get('myRoute', (req, res) => {
  req.i18n.changeLanguage(findLanguageByMyself(req))
  const video = await Video.findOne() // A time-consuming operation taking 1 second
  if (!video) return res.status(500).send(req.t('error505'));
})

Assume that the first request comes in at 0 second, and req.i18n.changeLanguage to "en", and it will wait asynchronously at await Video.findOne() for 1 second.
The second request comes in at 0.5 second, and req.i18n.changeLanguage to "de".
Then the first request finished await Video.findOne() at 1 second, and it gets a translation in req.t('error500'). Is this translation the "en" language?

Another small question is, in server use case, does i18next.init load all languages at the beginning?

adrai commented

yes, the i18n instance is a clone for each request: https://github.com/i18next/i18next-http-middleware/blob/master/lib/index.js#L39
but, honestly I would not call changeLanguage... better create an own languageDetector... like here: https://github.com/i18next/i18next-http-middleware/blob/master/lib/LanguageDetector.js
What do you mean by "does i18next.init load all languages at the beginning"?
If you set the preload option, it will load al languages on init: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources but if you want to wait for this to complete, you need to wait for the init callback or promise: https://www.i18next.com/overview/api#init

oney commented

Thanks for the answer!

adrai commented

If you like this module don’t forget to star this repo. Make a tweet, share the word or have a look at our https://locize.com to support the devs of this project.

There are many ways to help this project 🙏