{"id":17443,"library":"koa-i18next-middleware","title":"i18next Middleware for Koa 2","description":"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.","status":"abandoned","version":"1.1.12","language":"javascript","source_language":"en","source_url":"https://github.com/lxzxl/koa-i18next-middleware","tags":["javascript","i18","i18next","koa","koa2"],"install":[{"cmd":"npm install koa-i18next-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add koa-i18next-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-i18next-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core internationalization library that this middleware integrates with.","package":"i18next"},{"reason":"This is a Koa middleware and requires a Koa 2 application instance as a peer dependency.","package":"koa","optional":true},{"reason":"Required for session-based language detection methods (lookupSession, lookupMySession).","package":"koa-session","optional":true}],"imports":[{"note":"The package is primarily designed for CommonJS (`require`) usage. While ESM `import` might work via transpilation or bundlers, native ESM support is not guaranteed in older versions without explicit configuration.","wrong":"import * as i18m from 'koa-i18next-middleware';","symbol":"koa-i18next-middleware","correct":"const i18m = require('koa-i18next-middleware');"},{"note":"LanguageDetector is a named export from the main module. For ESM, prefer `import { LanguageDetector } from 'koa-i18next-middleware'` if the module exposes it this way, otherwise use `i18m.LanguageDetector` after a default import.","wrong":"import { LanguageDetector } from 'koa-i18next-middleware';","symbol":"LanguageDetector","correct":"const lngDetector = new i18m.LanguageDetector();"},{"note":"getHandler is a method exported from the main middleware module, not a top-level default export. It must be called on the imported `i18m` object.","wrong":"app.use(getHandler(i18next, options));","symbol":"getHandler","correct":"app.use(i18m.getHandler(i18next, options));"}],"quickstart":{"code":"const Koa = require('koa');\nconst i18next = require('i18next');\nconst i18m = require('koa-i18next-middleware');\nconst session = require('koa-session'); // Required for session-based detection\n\nconst app = new Koa();\napp.keys = ['some secret key']; // Required for koa-session\napp.use(session(app)); // Initialize session middleware\n\n// Add custom detector.\nconst lngDetector = new i18m.LanguageDetector();\nlngDetector.addDetector({\n    name: 'mySessionDetector',\n    lookup(ctx, options) {\n        let found;\n        if (options.lookupSession && ctx && ctx.session) {\n            found = ctx.session[options.lookupMySession];\n        }\n        return found;\n    },\n    cacheUserLanguage(ctx, lng, options = {}) {\n        if (options.lookupMySession && ctx && ctx.session) {\n            ctx.session[options.lookupMySession] = lng;\n        }\n    }\n});\n\ni18next.use(lngDetector).init(\n    {\n        fallbackLng: 'en',\n        preload: ['en', 'es'],\n        resources: {\n            en: {\n                translation: {\n                    key: 'hello world'\n                }\n            },\n            es: {\n                translation: {\n                    key: 'es hello world es'\n                }\n            }\n        },\n        detection: {\n            order: [\n                'querystring',\n                'path',\n                'cookie',\n                'session',\n                'mySessionDetector'\n            ],\n            lookupQuerystring: 'lng',\n            lookupParam: 'lng',\n            lookupFromPathIndex: 0,\n            lookupCookie: 'i18next',\n            lookupSession: 'lng',\n            lookupMySession: 'lang',\n            caches: ['cookie', 'mySessionDetector']\n        }\n    },\n    (err, t) => {\n        if (err) return console.error('i18next initialization failed', err);\n        console.log('i18next initialized. Example translation:', i18next.t('key'));\n    }\n);\n\napp.use(\n    i18m.getHandler(i18next, {\n        locals: 'locals',\n        ignoreRoutes: ['/no-lng-route']\n    })\n);\n\napp.use(async ctx => {\n    ctx.body = ctx.t('key'); // 'ctx.t' is provided by i18next\n});\n\nconst port = process.env.PORT || 3000;\napp.listen(port, () => console.log(`Koa app listening on port ${port}`));","lang":"javascript","description":"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."},"warnings":[{"fix":"Ensure your project uses Koa 2.x or later and Node.js v7.6.0+ (or 8.x+ for full async/await support) or transpile your code.","message":"This middleware is specifically designed for Koa 2 and requires Node.js versions that fully support async/await. It is not compatible with Koa 1.x or older Node.js runtimes.","severity":"breaking","affected_versions":"<1.0"},{"fix":"Proceed with caution. For new projects, evaluate more actively maintained alternatives like `i18next-http-middleware` (which can be used with Koa via `koaPlugin`). For existing projects, be prepared to fork or address compatibility issues manually.","message":"The `koa-i18next-middleware` project appears to be unmaintained. The last commit on its GitHub repository was approximately five years ago, and there have been no new releases since version 1.1.12. Users should be aware of the lack of ongoing support, bug fixes, or compatibility updates with newer Koa or Node.js versions. Consider `i18next-http-middleware` as a currently maintained alternative for Node.js frameworks like Koa.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Install `koa-session` (or a similar session middleware) and configure it like `app.use(session(app))` before `app.use(i18m.getHandler(...))`.","message":"When enabling session-based language detection (e.g., `lookupSession`, `lookupMySession`), a separate Koa session middleware (e.g., `koa-session`) must be installed and configured *before* `koa-i18next-middleware` in your Koa application's middleware stack. Otherwise, `ctx.session` will be undefined, leading to errors.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For basic detection, rely on built-in `i18next` detection options (querystring, cookie, header) which require less setup. Only implement custom detectors when complex logic is necessary.","message":"Configuring custom language detectors, as shown in the README, can be quite verbose and involves manually adding detector objects to the `i18m.LanguageDetector` instance. For simple use cases, this boilerplate might be excessive.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure your `app` object is an instance of `Koa()` from the `koa` package (version 2 or higher).","cause":"The middleware is being used with a non-Koa application instance, or an older Koa 1.x application, which does not have the async `app.use` signature.","error":"TypeError: app.use is not a function"},{"fix":"Install `koa-session` (or your chosen session middleware) via `npm i koa-session` and then add `app.keys = ['your-secret-key']; app.use(session(app));` to your Koa application before applying `koa-i18next-middleware`.","cause":"Session-based language detection methods (e.g., `lookupSession`, `lookupMySession`) are enabled in the `i18next` detection configuration, but a Koa session middleware (like `koa-session`) has not been installed or applied to the Koa app.","error":"TypeError: Cannot read properties of undefined (reading 'session') OR TypeError: ctx.session is undefined"},{"fix":"Ensure `i18next.init()` is called and its callback indicates readiness, or use async/await with `i18next.init()` to guarantee initialization completes before the middleware handler is registered with `app.use()`.","cause":"The `i18next.init()` method was not called or did not complete its asynchronous initialization before `i18m.getHandler()` was invoked.","error":"Error: i18next not initialized!"},{"fix":"Use `import * as i18m from 'koa-i18next-middleware';` for ESM imports. Alternatively, if your project allows, revert to CommonJS by removing `\"type\": \"module\"` from `package.json`.","cause":"Attempting to use `const i18m = require('koa-i18next-middleware');` syntax in a pure ECMAScript Module (ESM) context (i.e., `\"type\": \"module\"` in `package.json` without a `require` shim).","error":"ReferenceError: require is not defined"}],"ecosystem":"npm","meta_description":null}