i18next HTTP Backend

3.0.5 · active · verified Tue Apr 21

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import i18next from 'i18next';
import HttpBackend from 'i18next-http-backend';

// In a real application, translation files would be served from a web server.
// This example uses a mock fetch to simulate loading.
const mockTranslations = {
  en: {
    translation: {
      "welcome": "Welcome to our app!",
      "greeting": "Hello, {{name}}!"
    }
  },
  es: {
    translation: {
      "welcome": "¡Bienvenido a nuestra aplicación!",
      "greeting": "¡Hola, {{name}}!"
    }
  }
};

// Simulate a fetch function that would load resources from a URL
const mockFetch = async (url: string) => {
  console.log(`Simulating fetch for: ${url}`);
  const parts = url.split('/');
  const lang = parts[parts.length - 2]; // e.g., 'en' from '/locales/en/translation.json'
  const ns = parts[parts.length - 1].split('.')[0]; // e.g., 'translation'
  
  if (mockTranslations[lang as keyof typeof mockTranslations] && mockTranslations[lang as keyof typeof mockTranslations][ns as keyof typeof mockTranslations[keyof typeof mockTranslations]]) {
    return {
      ok: true,
      status: 200,
      json: () => Promise.resolve(mockTranslations[lang as keyof typeof mockTranslations][ns as keyof typeof mockTranslations[keyof typeof mockTranslations]])
    };
  }
  return {
    ok: false,
    status: 404,
    json: () => Promise.resolve({}) // Return empty object for 404
  };
};

i18next
  .use(HttpBackend)
  .init({
    lng: 'en',
    fallbackLng: 'en',
    debug: true, // Enable debug for more console output
    backend: {
      loadPath: '/locales/{{lng}}/{{ns}}.json',
      // Provide a custom request function to use the mock fetch
      request: (options, url, payload, callback) => {
        mockFetch(url)
          .then(response => {
            if (response.ok) {
              response.json().then(data => callback(null, { status: response.status, data }));
            } else {
              callback(new Error(`Failed to load ${url}: ${response.status}`), { status: response.status });
            }
          })
          .catch(error => callback(error, { status: 0 }));
      }
    },
    ns: ['translation'], // Default namespace
    defaultNS: 'translation',
    interpolation: {
      escapeValue: false, // React already escapes by default
    },
  })
  .then(() => {
    console.log(i18next.t('welcome'));
    console.log(i18next.t('greeting', { name: 'World' }));
    console.log(i18next.t('missingKey')); // This will show as 'missingKey' due to no translation
    
    // Change language and translate again
    i18next.changeLanguage('es').then(() => {
      console.log(i18next.t('welcome'));
    });
  })
  .catch((err) => console.error("i18next initialization error:", err));

view raw JSON →