i18next-http-backend Introduction
i18next-http-backend is a plugin for i18next that loads translation resources from remote servers. It supports HTTP requests, caching, and lazy loading.
Installation
bashnpm install i18next-http-backend # or yarn add i18next-http-backend
Basic Configuration
Simple Configuration
javascriptimport i18next from 'i18next'; import Backend from 'i18next-http-backend'; i18next .use(Backend) .init({ lng: 'en', fallbackLng: 'en', backend: { loadPath: '/locales/{{lng}}/{{ns}}.json' } });
Complete Configuration
javascripti18next .use(Backend) .init({ lng: 'en', fallbackLng: 'en', ns: ['translation', 'common', 'errors'], defaultNS: 'translation', backend: { loadPath: '/locales/{{lng}}/{{ns}}.json', addPath: '/locales/add/{{lng}}/{{ns}}', parse: (data, lng, ns) => { return JSON.parse(data); }, stringify: (data, lng, ns) => { return JSON.stringify(data); }, request: (options, url, payload, callback) => { // custom request logic fetch(url, options) .then(response => response.json()) .then(data => callback(null, { data, status: 200 })) .catch(error => callback(error, null)); }, reloadInterval: false, // reload interval (milliseconds) queryStringParams: { v: '1.0.0' } // add query parameters } });
Path Configuration
Dynamic Path Variables
{{lng}}: current language code{{ns}}: current namespace{{projectId}}: custom project ID
javascriptbackend: { loadPath: '/api/translations/{{lng}}/{{ns}}?projectId={{projectId}}', queryStringParams: { projectId: 'my-project-123' } }
Multiple Path Configuration
javascriptbackend: { loadPath: (lngs, namespaces) => { return namespaces.map(ns => `/locales/${lngs[0]}/${ns}.json`); } }
Lazy Loading
Load Namespaces on Demand
javascript// load only default namespace on initialization i18next .use(Backend) .init({ ns: ['translation'], defaultNS: 'translation' }); // load other namespaces when needed i18next.loadNamespaces(['admin', 'settings'], () => { console.log('Namespaces loaded'); });
Lazy Loading in React
javascriptimport { useTranslation } from 'react-i18next'; function AdminPanel() { const { t, ready } = useTranslation('admin', { useSuspense: false }); if (!ready) { return <div>Loading translations...</div>; } return <h1>{t('dashboard.title')}</h1>; }
Caching Mechanism
Use Local Storage Cache
javascriptimport LocalStorageBackend from 'i18next-localstorage-backend'; import Backend from 'i18next-http-backend'; i18next .use(Backend) .use(LocalStorageBackend) .init({ backend: { backends: [ LocalStorageBackend, // primary backend Backend // fallback backend ], backendOptions: [ { expirationTime: 7 * 24 * 60 * 60 * 1000, // 7 days defaultVersion: 'v1.0.0' }, { loadPath: '/locales/{{lng}}/{{ns}}.json' } ] } });
Custom Cache Logic
javascriptbackend: { loadPath: '/locales/{{lng}}/{{ns}}.json', request: (options, url, payload, callback) => { const cacheKey = `i18n_${url}`; const cached = localStorage.getItem(cacheKey); if (cached) { const { data, timestamp } = JSON.parse(cached); const isExpired = Date.now() - timestamp > 3600000; // 1 hour if (!isExpired) { return callback(null, { data, status: 200 }); } } fetch(url, options) .then(response => response.json()) .then(data => { localStorage.setItem(cacheKey, JSON.stringify({ data, timestamp: Date.now() })); callback(null, { data, status: 200 }); }) .catch(callback); } }
Error Handling
Load Failure Handling
javascripti18next .use(Backend) .init({ backend: { loadPath: '/locales/{{lng}}/{{ns}}.json' } }) .catch(err => { console.error('Translation resources failed to load:', err); // use fallback translations i18next.addResourceBundle('en', 'translation', { welcome: 'Welcome', error: 'An error occurred' }); });
Retry Mechanism
javascriptbackend: { loadPath: '/locales/{{lng}}/{{ns}}.json', request: (options, url, payload, callback) => { let retries = 3; const attemptFetch = (attempt) => { fetch(url, options) .then(response => response.json()) .then(data => callback(null, { data, status: 200 })) .catch(error => { if (attempt < retries) { setTimeout(() => attemptFetch(attempt + 1), 1000 * attempt); } else { callback(error, null); } }); }; attemptFetch(0); } }
Performance Optimization
Preload Critical Translations
javascripti18next .use(Backend) .init({ preload: ['en', 'zh'], // languages to preload ns: ['translation', 'common'] // namespaces to preload });
Batch Loading
javascript// load multiple namespaces at once Promise.all([ i18next.loadNamespaces(['admin', 'settings', 'reports']), i18next.loadLanguages(['en', 'zh', 'fr']) ]).then(() => { console.log('All translation resources loaded'); });
Best Practices
- Version Control: Add version parameters to URLs to avoid cache issues
- Error Handling: Implement comprehensive error handling and fallback mechanisms
- Performance Optimization: Use caching and lazy loading to reduce network requests
- Monitoring: Monitor translation resource loading performance and error rates
- CDN: Use CDN to accelerate translation resource loading