{"id":17746,"library":"koa-i18n","title":"Koa i18n Middleware","description":"koa-i18n is a lightweight internationalization (i18n) middleware for Koa applications, built upon the `i18n-2` library. The current stable version, 2.1.0, is designed for Koa 2.x, while a separate 1.x branch targets Koa 1.x applications. Release cadence appears to be tied to Koa's major versions, with `2.x` being the current 'next' major iteration as of its release 9 years ago. A key differentiator is its reliance on `koa-locale` for robust locale detection, supporting various strategies including query parameters, subdomains, cookies, HTTP headers (`Accept-Language`), URL segments, and top-level domains (TLD), with the flexibility to add custom detection functions. This allows developers to tailor how the application determines the user's preferred language, making it suitable for multi-lingual web services. It provides a simple API through `ctx.i18n.__()` for translating keys.","status":"maintenance","version":"2.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/koa-modules/koa-i18n","tags":["javascript","koa","locale","i18n","languages"],"install":[{"cmd":"npm install koa-i18n","lang":"bash","label":"npm"},{"cmd":"yarn add koa-i18n","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-i18n","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core translation logic for managing locales and string interpolation.","package":"i18n-2","optional":false},{"reason":"Mandatory prerequisite for locale detection from various sources (query, cookie, header, etc.). Must be initialized before koa-i18n.","package":"koa-locale","optional":false}],"imports":[{"note":"While the documentation primarily shows CommonJS `require()`, modern Koa applications (Node.js >= 7.6) can use ES module `import`. The package itself is transpiled to CJS.","wrong":"const i18n = require('koa-i18n');","symbol":"i18n","correct":"import i18n from 'koa-i18n';"},{"note":"The `locale` function is imported from `koa-locale`, a separate, mandatory dependency, and must be invoked with the Koa app instance before `koa-i18n` middleware is applied.","wrong":"import i18n, { locale } from 'koa-i18n';","symbol":"locale","correct":"import locale from 'koa-locale';\n// then:\nlocale(app);"},{"note":"The translation function is exposed on the Koa context under the `i18n` property, as `ctx.i18n.__`. Direct access via `ctx.__` is incorrect unless explicitly configured otherwise by another middleware.","wrong":"ctx.body = ctx.__('my.translation.key');","symbol":"ctx.i18n.__","correct":"ctx.body = ctx.i18n.__('my.translation.key', 'value1', 'value2');"}],"quickstart":{"code":"const Koa = require('koa');\nconst convert = require('koa-convert'); // Used for generator-based middleware compatibility\nconst locale = require('koa-locale'); // Essential for locale detection\nconst i18n = require('koa-i18n');\n\nconst app = new Koa();\n\n// IMPORTANT: koa-locale must be initialized before koa-i18n\nlocale(app);\n\napp.use(i18n(app, {\n  directory: './config/locales', // Path to your locale files (e.g., zh-CN.json, en.json)\n  locales: ['zh-CN', 'en'], // List of supported locales; defaultLocale should match a filename\n  modes: [\n    'query',      // Detect locale from query string: /?locale=en\n    'subdomain',  // Detect locale from subdomain: en.myapp.com\n    'cookie',     // Detect locale from cookie: Cookie: locale=zh-TW\n    'header',     // Detect locale from Accept-Language header\n    'url',        // Detect locale from URL path: /en/page\n    'tld',        // Detect locale from top-level domain: myapp.cn\n    function() { /* optional custom detection logic */ }\n  ]\n}));\n\napp.use(async (ctx, next) => {\n  // Access translated strings via ctx.i18n.__\n  ctx.body = ctx.i18n.__('greeting'); // Assuming 'greeting' key in your locale files\n  await next();\n});\n\n// Example using koa-convert for older generator-style middleware (optional)\napp.use(convert(function *() {\n  // Yield a render if you have a view engine configured\n  // yield this.render('index', { title: this.i18n.__('pageTitle') });\n}));\n\napp.listen(3000, () => {\n  console.log('Koa i18n app running on http://localhost:3000');\n});\n\n// Example locale file structure (e.g., ./config/locales/en.json):\n// {\"greeting\": \"Hello, Koa!\", \"pageTitle\": \"Welcome\"}","lang":"javascript","description":"Demonstrates setting up `koa-i18n` middleware, initializing `koa-locale`, configuring locale detection modes, and performing basic string translation within a Koa application context. Includes a note on legacy `koa-convert` usage."},"warnings":[{"fix":"For Koa 2.x+, ensure `koa-i18n@2.x` is installed. Modern Koa 2.x+ middleware should be `async (ctx, next) => { ... }` functions. Remove `koa-convert` if your middleware is already async/await.","message":"`koa-i18n` has distinct major versions for different Koa versions: `koa-i18n@1.x` for Koa 1.x (generator-based middleware) and `koa-i18n@2.x` for Koa 2.x+ (async/await middleware). Ensure you install the correct version matching your Koa setup. The example in the README uses `koa-convert` to adapt generator functions to Koa 2.x's async middleware style, which is often not needed in purely async/await Koa 2.x+ applications.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Ensure `const locale = require('koa-locale');` and `locale(app);` are present and executed before `app.use(i18n(app, {...}));`.","message":"The `koa-locale` package is a mandatory dependency and *must* be initialized by calling `locale(app)` before `koa-i18n` is used as middleware. Failing to do so will result in runtime errors as `koa-i18n` depends on `koa-locale` to set up locale detection on the Koa application context.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Verify that entries in the `locales` array directly correspond to your locale filenames (excluding the file extension) in the `directory`.","message":"The `locales` array in the configuration must precisely match the filenames of your locale definition files (e.g., `['zh-CN', 'en']` expects `./config/locales/zh-CN.json` and `./config/locales/en.json`). Mismatched names can lead to `koa-i18n` failing to load translations or falling back to an unexpected default.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Arrange the `modes` array with the highest priority detection methods at the beginning (e.g., 'query' often before 'header').","message":"When configuring locale detection `modes`, the order matters. The first mode that successfully detects a locale will be used, and subsequent modes will be ignored. Place your preferred or most specific detection methods earlier in the array.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For new projects or if encountering limitations, evaluate more actively maintained i18n solutions for Koa, such as `koa-i18next` or `koa-i18n-next`.","message":"The package `koa-i18n` has not been updated in approximately 9 years. While functional, it might not leverage the latest Node.js features, Koa 3.x paradigms, or modern i18n practices like ICU MessageFormat or more advanced pluralization rules found in newer libraries. Consider alternatives like `koa-i18next` for more active development and features.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure `locale(app);` is called before `app.use(i18n(app, {...}));`. Also, confirm `app.use(i18n(...))` is present and correctly configured.","cause":"`koa-i18n` middleware was not correctly applied, or `koa-locale` was not initialized before `koa-i18n`.","error":"TypeError: ctx.i18n.__ is not a function"},{"fix":"Add `locale(app);` before `app.use(i18n(app, {...}));`. Ensure `koa-locale` is a dependency and correctly imported/required.","cause":"`koa-locale` was imported/required but its initialization function `locale(app)` was not called or was called after `koa-i18n` was used.","error":"Error: koa-locale must be required!"},{"fix":"Verify the key `some.key` exists in your locale file (e.g., `en.json`). Check the `directory` path in `koa-i18n` options and ensure `locales` array matches the filenames. The `i18n-2` dependency `koa-i18n` uses does not support best-match fallbacks, only exact locale matches.","cause":"The specified translation key does not exist in the active locale's file, or the locale files are not correctly loaded due to `directory` or `locales` configuration issues.","error":"Translations for key 'some.key' not found in locale 'en'"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}