i18next / i18next-express-middleware

[deprecated] can be replaced with i18next-http-middleware
https://github.com/i18next/i18next-http-middleware
MIT License
206 stars 52 forks source link

Cloning and triggering init() at each http request? #134

Closed jfstgermain closed 7 years ago

jfstgermain commented 7 years ago

Hello, I enabled the i18next debug mode and kept seeing i18next initialization messages at each request. After digging in the middleware code I saw that i18next is being cloned and initialized for each request!

That could become an issue depending on the backend being used not to mention that it renders the translation caching (preloading) useless (it seems that the backend initialization routine is also triggered down the road)... Is there a particular reason why this was done in this fashion instead of passing a language code around and only using one instance of i18next? My usage is pretty basic for now, I only use the t() function but what about something like:

// init i18next..

function middleware (req, res, next) {
  req.i18n = {
    t: (keys, options = {}) => {
      if (!req.lng && i18next.services.languageDetector) {
        req.lng = i18next.services.languageDetector.detect(req, res);
        req.language = req.lng;
        req.locale = req.lng;
      }

      options.lng = req.lng;

      return i18next.t(keys, options);
    },
  };

  next();
}
jfstgermain commented 7 years ago

Seems like i18next.getFixedT() does the same thing

jamuhl commented 7 years ago

We used to have the getFixedT in the old days we had no option to create new instances of i18next.

The instance that get created is using the cloneInstance function: https://www.i18next.com/api.html#cloneinstance

So there is no new initialization of backend or loading of translations (if already loaded/preloaded).