i18next Middleware for Koa 2

1.1.12 · abandoned · verified Wed Apr 22

koa-i18next-middleware is a specialized middleware designed to integrate the i18next internationalization (i18n) library with Koa 2 applications. It enables dynamic language detection within Koa APIs, supporting various strategies such as reading from querystring parameters, URL path segments, cookies, and sessions. The middleware also offers the flexibility to define custom language detection mechanisms. The current stable version, 1.1.12, has seen no significant updates for several years, with the last activity on its GitHub repository dating back approximately five years. This indicates that the project is largely unmaintained, and users should be cautious regarding long-term support, security patches, or compatibility with newer Node.js or Koa versions. Its primary utility lies in providing a direct, Koa-idiomatic integration for i18next's language detection and translation capabilities, catering specifically to the Koa 2 async/await paradigm.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize i18next, configure koa-i18next-middleware with a custom language detector, and apply it to a Koa 2 application, including session setup for detection.

const Koa = require('koa');
const i18next = require('i18next');
const i18m = require('koa-i18next-middleware');
const session = require('koa-session'); // Required for session-based detection

const app = new Koa();
app.keys = ['some secret key']; // Required for koa-session
app.use(session(app)); // Initialize session middleware

// Add custom detector.
const lngDetector = new i18m.LanguageDetector();
lngDetector.addDetector({
    name: 'mySessionDetector',
    lookup(ctx, options) {
        let found;
        if (options.lookupSession && ctx && ctx.session) {
            found = ctx.session[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',
                'cookie',
                'session',
                'mySessionDetector'
            ],
            lookupQuerystring: 'lng',
            lookupParam: 'lng',
            lookupFromPathIndex: 0,
            lookupCookie: 'i18next',
            lookupSession: 'lng',
            lookupMySession: 'lang',
            caches: ['cookie', 'mySessionDetector']
        }
    },
    (err, t) => {
        if (err) return console.error('i18next initialization failed', err);
        console.log('i18next initialized. Example translation:', i18next.t('key'));
    }
);

app.use(
    i18m.getHandler(i18next, {
        locals: 'locals',
        ignoreRoutes: ['/no-lng-route']
    })
);

app.use(async ctx => {
    ctx.body = ctx.t('key'); // 'ctx.t' is provided by i18next
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Koa app listening on port ${port}`));

view raw JSON →