I have set up the i18n middleware in my Express Node js server like this:
JavaScript
x
27
27
1
// server.js
2
import i18nMiddleware from 'i18next-express-middleware';
3
import i18n from 'i18next';
4
import Backend from 'i18next-node-fs-backend';
5
import { LanguageDetector } from 'i18next-express-middleware';
6
7
i18n
8
.use(Backend)
9
.use(LanguageDetector)
10
.init({
11
whitelist: ['en', 'my'],
12
fallbackLng: 'en',
13
14
// have a common namespace used around the full app
15
ns: ['common'],
16
defaultNS: 'common',
17
18
debug: false,
19
20
backend: {
21
loadPath: './locales/{{lng}}/{{ns}}.json',
22
// jsonIndent: 2
23
}
24
});
25
26
app.use(i18nMiddleware.handle(i18n))
27
Here is the translation test file:
JavaScript
1
10
10
1
// test.js
2
import i18next from "i18next";
3
4
const test = (req, res) =>{
5
const t = req.i18n.t.bind(i18next);
6
7
console.log(req.i18n.language) // language set correctly :)
8
console.log(t('title')) // translation not working :(
9
}
10
The value of title in English is title and for Malaysian, it’s tajuk
As per the express middleware documentation, I’m passing my as the accept-language header , and console.log(req.i18n.language)
is correctly printing it.
However, console.log(t('title'))
is still printing title instead of tajuk
Advertisement
Answer
This looks crazy but this solved the problem:
JavaScript
1
3
1
const i18n = req.i18n;
2
console.log(i18n.t('title'))
3