{"id":17709,"library":"i18next-http-middleware","title":"i18next HTTP Middleware","description":"i18next-http-middleware is a versatile, framework-agnostic middleware for integrating i18next into Node.js web applications (Express, Fastify, Hapi) and Deno. Currently at version 3.9.5, it is actively maintained with regular updates, with the last major update to 3.x series being 2 months ago. This package serves as a modern drop-in replacement for the deprecated `i18next-express-middleware`, offering broader compatibility beyond just Express. It facilitates language detection from various request sources (path, cookie, header, querystring, session) and injects the i18next instance directly onto the request object, providing methods like `req.t()`, `req.language`, and `req.languages` for seamless internationalization within server-side handlers and views. Its primary differentiator is its flexibility across different HTTP frameworks and its close integration with the i18next ecosystem for robust server-side internationalization.","status":"active","version":"3.9.5","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/i18next/i18next-http-middleware","tags":["javascript","i18next","i18next-backend","i18next-http-middleware","express","typescript"],"install":[{"cmd":"npm install i18next-http-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add i18next-http-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add i18next-http-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core i18n library that this middleware integrates with and extends. It's an implicit peer dependency for all functionality.","package":"i18next","optional":false}],"imports":[{"note":"Primary middleware function for Express and generic Node.js HTTP servers. Named export.","wrong":"const handle = require('i18next-http-middleware').handle;","symbol":"handle","correct":"import { handle } from 'i18next-http-middleware';"},{"note":"A plugin for i18next to detect user language from HTTP request properties. Named export, used via `i18next.use()`.","wrong":"const LanguageDetector = require('i18next-http-middleware').LanguageDetector;","symbol":"LanguageDetector","correct":"import { LanguageDetector } from 'i18next-http-middleware';"},{"note":"Fastify-specific plugin for integration via `app.register()`. Named export.","wrong":"const plugin = require('i18next-http-middleware').plugin;","symbol":"plugin","correct":"import { plugin } from 'i18next-http-middleware';"},{"note":"Hapi.js-specific plugin for integration via `server.register()`. Named export.","wrong":"const hapiPlugin = require('i18next-http-middleware').hapiPlugin;","symbol":"hapiPlugin","correct":"import { hapiPlugin } from 'i18next-http-middleware';"}],"quickstart":{"code":"import express from 'express';\nimport i18next from 'i18next';\nimport { LanguageDetector, handle } from 'i18next-http-middleware';\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\n// Initialize i18next with the language detector and some translations\ni18next.use(LanguageDetector).init({\n  preload: ['en', 'de', 'fr'],\n  fallbackLng: 'en',\n  debug: true,\n  resources: {\n    en: {\n      translation: {\n        welcome: 'Hello world!',\n        greeting: 'Welcome to our internationalized app!',\n        howAreYou: 'How are you?'\n      }\n    },\n    de: {\n      translation: {\n        welcome: 'Hallo Welt!',\n        greeting: 'Willkommen in unserer internationalisierten App!',\n        howAreYou: 'Wie geht es dir?'\n      }\n    },\n    fr: {\n      translation: {\n        welcome: 'Bonjour le monde!',\n        greeting: 'Bienvenue dans notre application internationalisée!',\n        howAreYou: 'Comment allez-vous?'\n      }\n    }\n  }\n});\n\n// Apply the i18next-http-middleware\napp.use(handle(i18next, {\n  ignoreRoutes: ['/health'], // Example: ignore specific routes from i18n processing\n  removeLngFromUrl: false // Set to true if language is part of the URL path (e.g., /en/home)\n}));\n\n// Example route demonstrating i18n usage\napp.get('/', (req, res) => {\n  // Access i18n properties from the request object\n  const language = req.language || 'en';\n  const translatedGreeting = req.t('greeting');\n  const translatedWelcome = req.t('welcome');\n\n  res.send(`\n    <h1>${translatedWelcome}</h1>\n    <p>${translatedGreeting}</p>\n    <p>Current language: <strong>${language}</strong></p>\n    <p>Detected languages: ${req.languages?.join(', ') || 'N/A'}</p>\n    <p>Try going to <a href=\"/de\">/de</a> or <a href=\"/fr\">/fr</a></p>\n  `);\n});\n\n// Example route for a specific language path segment (if LanguageDetector is configured for path)\napp.get('/:lng', (req, res, next) => {\n  // The middleware would have already set req.language based on the path if configured\n  // For this example, we just render the root path again with the detected language\n  if (['en', 'de', 'fr'].includes(req.params.lng)) {\n      return res.redirect('/');\n  }\n  next(); // Pass to next handler if not a language code\n});\n\n// Health check route, ignored by i18n middleware\napp.get('/health', (req, res) => {\n  res.send('OK');\n});\n\napp.listen(PORT, () => {\n  console.log(`Server listening on http://localhost:${PORT}`);\n  console.log('Test with:');\n  console.log(`- http://localhost:${PORT}/en`);\n  console.log(`- http://localhost:${PORT}/de`);\n  console.log(`- http://localhost:${PORT}/fr`);\n  console.log(`- http://localhost:${PORT}?lng=fr`);\n  console.log(`- curl -H \"Accept-Language: de\" http://localhost:${PORT}`);\n});","lang":"typescript","description":"This example sets up `i18next-http-middleware` with an Express server, initializing i18next with multiple languages and preloaded resources. It demonstrates applying the middleware globally, accessing translation functions (`req.t`) and language properties (`req.language`, `req.languages`) from the request object, and handles basic routing for language switching based on URL path or query parameters. It also includes an ignored health check route."},"warnings":[{"fix":"Upgrade to `i18next-http-middleware` version 3.9.3 or higher immediately. This version introduces robust sanitization of control characters and a strengthened XSS regex to mitigate these vulnerabilities.","message":"Versions of `i18next-http-middleware` prior to 3.9.3 are vulnerable to HTTP response splitting, denial of service (DoS) in Node.js >= 14.6.0, and reflected XSS. This is due to insufficient sanitization of the `Content-Language` header and a weak XSS filter that could be bypassed by certain payloads.","severity":"breaking","affected_versions":"<3.9.3"},{"fix":"Migrate from `i18next-express-middleware` to `i18next-http-middleware`. Ensure you update your imports and middleware registration according to the new package's documentation, taking advantage of its broader framework support.","message":"This package is the recommended replacement for the deprecated `i18next-express-middleware`. While it is designed as a drop-in replacement, it offers enhanced framework-agnostic usage and updated internals.","severity":"deprecated","affected_versions":">=1.0.0"},{"fix":"Ensure all necessary languages are either `preload`ed in your `i18next.init()` configuration or that you have an i18next backend (e.g., `i18next-fs-backend`, `i18next-http-backend`) properly configured to fetch missing translations. To persist language changes across requests, you typically need to update a cookie or session via client-side or server-side logic outside of `req.i18n.changeLanguage()`.","message":"Calling `req.i18n.changeLanguage('someCode')` within a request handler will only change the language instance for the current request's context. It will NOT dynamically load new translation resources if they haven't been preloaded or configured to load on demand via an i18next backend. Translations for the newly set language might be missing if not present.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If experiencing this issue, upgrade to `i18next-http-middleware` version 3.8.2 or later, which includes a fix for this bug. Alternatively, configure `fallbackLng` as a simple array (e.g., `['en']`) to avoid the error in affected versions.","message":"In `i18next-http-middleware` v3.8.1, configuring `fallbackLng` as an object (e.g., `{ default: ['en'] }`) could lead to a `TypeError` due to incorrect handling of the object structure by the LanguageDetector. This was a regression from previous versions.","severity":"gotcha","affected_versions":"3.8.1"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Upgrade `i18next-http-middleware` to version 3.8.2 or newer. As a workaround for affected versions, configure `fallbackLng` as an array (e.g., `fallbackLng: ['en']`) instead of an object.","cause":"This error typically occurs in `i18next-http-middleware` version 3.8.1 when `fallbackLng` is configured as an object in your i18next initialization options, which the `LanguageDetector` did not correctly process.","error":"TypeError: _this.fallbacks.map is not a function"},{"fix":"Verify that the language you are switching to is included in `preload` in your `i18next.init()` configuration, or ensure your i18next setup includes a backend that can asynchronously load resources for new languages. To persist language changes across requests, you typically need to update a user's language preference in a cookie or session, which the `LanguageDetector` can then pick up on subsequent requests.","cause":"The `changeLanguage` call on the request-scoped i18n instance does not trigger loading of new resources by default; it only sets the active language for that request if resources are already available locally (e.g., preloaded).","error":"Translations not updating after calling req.i18n.changeLanguage()"},{"fix":"Ensure you have called `app.use(handle(i18next, ...))` for Express, `app.register(i18nextMiddleware.plugin, ...)` for Fastify, or `server.register({ plugin: i18nextMiddleware.hapiPlugin, ...})` for Hapi, and that `i18next` itself is initialized with `i18next.use(LanguageDetector).init(...)` before applying the middleware to your application's request pipeline.","cause":"This usually indicates that the `i18next-http-middleware` has not been properly initialized or applied to your Express/Fastify/Hapi app *before* your route handlers attempt to access `req.i18n` or related properties.","error":"TypeError: Cannot read properties of undefined (reading 't') or (reading 'language')"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}