In my server's routes, I do something like this (Note: The i18next-express-middleware
is already in the pipeline, and Server Side Rendering is working good):
export default function (req, res) {
const lng = req.language.toUpperCase()
console.log(lng) // Always display [EN]
MyModel
.findOne(query, { fieldEN: 1, fieldFR: 1 })
.exec()
.then(res => reply(res[`field${lng}`]))
.catch(err => handle(err))
}
So I try to return the right version of the field, base on the USER's selected language.
But no matter what language is selected on the browser side, on the server side it is always set to the default, EN.
Is there a way to let the server side LanguageDetector
know about the current language on the browser side ?
This is my Client i18n init
:
import i18n from 'i18next'
import Backend from 'i18next-xhr-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
i18n
.use(Backend)
.use(LanguageDetector)
.init({
whitelist: ['en', 'fr'],
fallbackLng: 'en',
preload: ['en', 'fr'],
// debug: true,
interpolation: {
escapeValue: false
},
ns: ['home', 'channel', 'common'],
defaultNS: 'home',
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json'
},
react: {
wait: true,
bindI18n: 'languageChanged loaded',
bindStore: 'added removed',
nsMode: 'default'
}
})
export default i18n
And this is my server i18n init
:
import i18n from 'i18next'
import Backend from 'i18next-node-fs-backend'
import { LanguageDetector } from 'i18next-express-middleware'
i18n
.use(Backend)
.use(LanguageDetector)
.init({
whitelist: ['en', 'fr'],
fallbackLng: 'en',
preload: ['en', 'fr'],
// debug: true,
interpolation: {
escapeValue: false
},
ns: ['home', 'channel', 'common'],
defaultNS: 'home',
backend: {
loadPath: `${__dirname}/public/locales/{{lng}}/{{ns}}.json`,
jsonIndent: 2
}
})
export default i18n
Guess issue on github https://github.com/i18next/react-i18next/issues/471 gives the answer...
And no stackoverflow...i won't write the full reply here again ;)
With code pasted here it will / should work...but reading above issue - there is a missing piece - creating a new instance (beside the one getting in req) and setting the language there -> leads to desync if relying on detection and not setting initialLanguage right...