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.
npm install koa-i18nVerified import paths — ran on the pinned version, not inferred.
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.
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.Ensure `const locale = require('koa-locale');` and `locale(app);` are present and executed before `app.use(i18n(app, {...}));`.Verify that entries in the `locales` array directly correspond to your locale filenames (excluding the file extension) in the `directory`.
Arrange the `modes` array with the highest priority detection methods at the beginning (e.g., 'query' often before 'header').
For new projects or if encountering limitations, evaluate more actively maintained i18n solutions for Koa, such as `koa-i18next` or `koa-i18n-next`.
Ensure `locale(app);` is called before `app.use(i18n(app, {...}));`. Also, confirm `app.use(i18n(...))` is present and correctly configured.Add `locale(app);` before `app.use(i18n(app, {...}));`. Ensure `koa-locale` is a dependency and correctly imported/required.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.