{"id":16083,"library":"i18next-http-backend","title":"i18next HTTP Backend","description":"i18next-http-backend is a backend layer for the i18next internationalization framework, designed to load translation resources from a remote server using standard HTTP requests (XMLHttpRequest or Fetch API). It supports diverse JavaScript environments, functioning seamlessly in Node.js, modern browsers, and Deno. Currently at stable version 3.0.5, it receives updates as needed to maintain compatibility and introduce improvements. It's explicitly designed as a modern, drop-in replacement for the deprecated i18next-xhr-backend, addressing its limitations. Its primary differentiation is its broad platform support and direct integration with i18next's resource loading mechanism, enabling developers to manage translations externally without bundling them into the client-side application. It offers configurable options for request handling, retry logic, and resource path resolution.","status":"active","version":"3.0.5","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/i18next/i18next-http-backend","tags":["javascript","i18next","i18next-backend","i18next-http-backend","typescript"],"install":[{"cmd":"npm install i18next-http-backend","lang":"bash","label":"npm"},{"cmd":"yarn add i18next-http-backend","lang":"bash","label":"yarn"},{"cmd":"pnpm add i18next-http-backend","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core internationalization framework this backend integrates with.","package":"i18next","optional":false}],"imports":[{"note":"The HttpBackend class is exported as the default export of the package.","wrong":"import { HttpBackend } from 'i18next-http-backend';","symbol":"HttpBackend","correct":"import HttpBackend from 'i18next-http-backend';"},{"note":"In CommonJS, the default export is directly assigned when requiring the module.","wrong":"const HttpBackend = require('i18next-http-backend').default;","symbol":"HttpBackend (CommonJS)","correct":"const HttpBackend = require('i18next-http-backend');"},{"note":"TypeScript users can import this interface for configuring the HttpBackend.","symbol":"HttpBackendOptions (Type)","correct":"import type { HttpBackendOptions } from 'i18next-http-backend';"}],"quickstart":{"code":"import i18next from 'i18next';\nimport HttpBackend from 'i18next-http-backend';\n\n// In a real application, translation files would be served from a web server.\n// This example uses a mock fetch to simulate loading.\nconst mockTranslations = {\n  en: {\n    translation: {\n      \"welcome\": \"Welcome to our app!\",\n      \"greeting\": \"Hello, {{name}}!\"\n    }\n  },\n  es: {\n    translation: {\n      \"welcome\": \"¡Bienvenido a nuestra aplicación!\",\n      \"greeting\": \"¡Hola, {{name}}!\"\n    }\n  }\n};\n\n// Simulate a fetch function that would load resources from a URL\nconst mockFetch = async (url: string) => {\n  console.log(`Simulating fetch for: ${url}`);\n  const parts = url.split('/');\n  const lang = parts[parts.length - 2]; // e.g., 'en' from '/locales/en/translation.json'\n  const ns = parts[parts.length - 1].split('.')[0]; // e.g., 'translation'\n  \n  if (mockTranslations[lang as keyof typeof mockTranslations] && mockTranslations[lang as keyof typeof mockTranslations][ns as keyof typeof mockTranslations[keyof typeof mockTranslations]]) {\n    return {\n      ok: true,\n      status: 200,\n      json: () => Promise.resolve(mockTranslations[lang as keyof typeof mockTranslations][ns as keyof typeof mockTranslations[keyof typeof mockTranslations]])\n    };\n  }\n  return {\n    ok: false,\n    status: 404,\n    json: () => Promise.resolve({}) // Return empty object for 404\n  };\n};\n\ni18next\n  .use(HttpBackend)\n  .init({\n    lng: 'en',\n    fallbackLng: 'en',\n    debug: true, // Enable debug for more console output\n    backend: {\n      loadPath: '/locales/{{lng}}/{{ns}}.json',\n      // Provide a custom request function to use the mock fetch\n      request: (options, url, payload, callback) => {\n        mockFetch(url)\n          .then(response => {\n            if (response.ok) {\n              response.json().then(data => callback(null, { status: response.status, data }));\n            } else {\n              callback(new Error(`Failed to load ${url}: ${response.status}`), { status: response.status });\n            }\n          })\n          .catch(error => callback(error, { status: 0 }));\n      }\n    },\n    ns: ['translation'], // Default namespace\n    defaultNS: 'translation',\n    interpolation: {\n      escapeValue: false, // React already escapes by default\n    },\n  })\n  .then(() => {\n    console.log(i18next.t('welcome'));\n    console.log(i18next.t('greeting', { name: 'World' }));\n    console.log(i18next.t('missingKey')); // This will show as 'missingKey' due to no translation\n    \n    // Change language and translate again\n    i18next.changeLanguage('es').then(() => {\n      console.log(i18next.t('welcome'));\n    });\n  })\n  .catch((err) => console.error(\"i18next initialization error:\", err));\n","lang":"typescript","description":"This quickstart demonstrates how to initialize i18next with the HttpBackend, configuring it to load translation files from a specified path. It shows how to set up namespaces, fallback languages, and perform basic translation lookups, including changing the active language, using a mock fetch for a runnable example."},"warnings":[{"fix":"Replace `i18next-xhr-backend` with `i18next-http-backend`. Review any custom `loadPath` or `request` options, especially if they implicitly relied on XHR-specific behaviors or relied on older browser XMLHttpRequest APIs directly. Ensure proper polyfills are in place for Fetch API if targeting very old browsers.","message":"i18next-http-backend is a direct replacement for the deprecated i18next-xhr-backend. While largely a drop-in replacement, be aware of subtle differences in how HTTP requests are handled (Fetch API vs. XMLHttpRequest) which might affect custom configurations or older browser compatibility if not properly polyfilled.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Set `i18next.init({ load: 'languageOnly' })` to instruct i18next to only load the base language (e.g., 'en') and ignore region specifics ('-US'). Alternatively, ensure you provide translations for all detected regional variants or configure the language detector to be less specific.","message":"Encountering 404 errors for region-specific languages (e.g., requesting 'en-US' when only 'en' translations are provided) is a common issue. This often happens if an i18next language detector is active and the `load` option is set to its default 'all'.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"First, debug and resolve the underlying HTTP request issues (e.g., incorrect `backend.loadPath`, misconfigured server, CORS issues). If transient failures are expected, you can configure `i18next.init({ retryTimeout: 350, maxRetries: 1 })` to reduce the number of retry attempts and speed up the fallback process.","message":"Slow i18next initialization can occur if HTTP requests for translation files fail. i18next is configured to retry these requests multiple times by default, leading to delays before it completes initialization.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For ESM environments without top-level await support, import the CommonJS (CJS) export: `import HttpBackend from 'i18next-http-backend/cjs';`. Ensure you are on the latest patch release (e.g., 3.0.5) to benefit from security fixes related to URL construction and log forging.","message":"Version 3.0.0 introduced breaking changes for ESM build environments that do not support top-level await, and addressed security vulnerabilities.","severity":"gotcha","affected_versions":">=3.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Set `i18next.init({ load: 'languageOnly' })` to prevent requests for region-specific languages. Verify `backend.loadPath` is correct and that your server is configured to serve the translation files at that path with appropriate CORS headers.","cause":"A language detector requests a region-specific language (e.g., 'en-US') for which no translation is provided, the 'loadPath' is incorrect, or the backend server is not serving the files.","error":"Seeing failed http requests, like 404?"},{"fix":"Analyze HTTP requests and fix the root cause (e.g., incorrect `loadPath`, server misconfiguration). Alternatively, configure `i18next.init({ retryTimeout: 350, maxRetries: 1 })` to reduce retry attempts and hasten initialization when requests are failing.","cause":"HTTP requests for translation files are failing, causing i18next to retry multiple times before giving up, leading to delays.","error":"Slow i18next initialization?"}],"ecosystem":"npm"}