An i18next middleware for koa2 framework.
const i18next = require('i18next');
const i18m = require('koa-i18next-middleware');
const lngDetector = new i18m.LanguageDetector();
lngDetector.addDetector({
name: 'mySessionDetector',
lookup(ctx, options) {
let found;
if (options.lookupSession && ctx && ctx.sessions) {
found = ctx.sessions[options.lookupMySession];
}
return found;
},
cacheUserLanguage(ctx, lng, options = {}) {
if (options.lookupMySession && ctx && ctx.session) {
ctx.session[options.lookupMySession] = lng;
}
}
});
i18next.use(lngDetector).init(
{
fallbackLng: 'en',
preload: ['en', 'es'],
resources: {
en: {
translation: {
key: 'hello world'
}
},
es: {
translation: {
key: 'es hello world es'
}
}
},
detection: {
order: [
'querystring',
'path',
'session',
'mySessionDetector'
],
lookupQuerystring: 'lng',
lookupParam: 'lng',
lookupFromPathIndex: 0,
lookupCookie: 'i18next',
lookupSession: 'lng',
lookupMySession: 'lang',
caches: ['cookie', 'mySessionDetector']
}
},
(err, t) => {
const hw = i18next.t('key');
console.log(hw);
}
);
app.use(
i18m.getHandler(i18next, {
locals: 'locals',
ignoreRoutes: ['/no-lng-route']
})
);