What is i18next-http-backend?
The i18next-http-backend package is a backend layer for the i18next internationalization framework, allowing you to load translations from a remote server via HTTP(S). It is particularly useful for applications that need to fetch translations dynamically from a server, making it easier to manage and update translations without redeploying the application.
What are i18next-http-backend's main functionalities?
Loading Translations from a Remote Server
This feature allows you to load translation files from a remote server. The `loadPath` option specifies the URL pattern to fetch the translation files, where `{{lng}}` and `{{ns}}` are placeholders for the language and namespace, respectively.
const i18next = require('i18next');
const HttpBackend = require('i18next-http-backend');
i18next
.use(HttpBackend)
.init({
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json'
}
});
Customizing HTTP Requests
This feature allows you to customize the HTTP requests used to fetch the translation files. The `requestOptions` object can include any options that are valid for the Fetch API, such as `mode`, `credentials`, and `cache`.
const i18next = require('i18next');
const HttpBackend = require('i18next-http-backend');
i18next
.use(HttpBackend)
.init({
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json',
requestOptions: {
mode: 'cors',
credentials: 'same-origin',
cache: 'default'
}
}
});
Handling Load Errors
This feature allows you to handle errors that occur during the loading of translation files. The `request` function can be customized to handle different types of errors and provide appropriate responses.
const i18next = require('i18next');
const HttpBackend = require('i18next-http-backend');
i18next
.use(HttpBackend)
.init({
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json',
request: (options, url, payload, callback) => {
fetch(url, options)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => callback(null, { status: '200', data }))
.catch(error => callback(error, { status: '500' }));
}
}
});
Other packages similar to i18next-http-backend
i18next-fs-backend
The i18next-fs-backend package is another backend layer for i18next, but it loads translations from the file system instead of a remote server. This is useful for server-side applications where translations are stored locally. Compared to i18next-http-backend, it does not support dynamic loading from a remote server.
i18next-localstorage-backend
The i18next-localstorage-backend package allows you to cache translations in the browser's local storage. This can improve performance by reducing the number of HTTP requests needed to fetch translations. However, it does not provide the same level of dynamic loading from a remote server as i18next-http-backend.
i18next-xhr-backend
The i18next-xhr-backend package is similar to i18next-http-backend but uses XMLHttpRequest instead of the Fetch API to load translations. It provides similar functionality but may be less modern and flexible compared to i18next-http-backend, which leverages the Fetch API.
Introduction
This is a simple i18next backend to be used in Node.js, in the browser and for Deno. It will load resources from a backend server using the XMLHttpRequest or the fetch API.
Get a first idea on how it is used in this i18next crash course video.
It's based on the deprecated i18next-xhr-backend and can mostly be used as a drop-in replacement.
Why i18next-xhr-backend was deprecated?
Advice:
If you don't like to manage your translation files manually or are simply looking for a better management solution, take a look at i18next-locize-backend. The i18next backed plugin for 🌐 locize ☁️.
To see i18next-locize-backend in a working app example, check out:
Troubleshooting
Make sure you set the debug
option of i18next to true
. This will maybe log more information in the developer console.
Seeing failed http requests, like 404?
Are you using a language detector plugin that detects region specific languages you are not providing? i.e. you provide 'en'
translations but you see a 'en-US'
request first?
This is because of the default load
option set to 'all'
.
Try to set the load
option to 'languageOnly'
i18next.init({
load: 'languageOnly',
})
Getting started
Source can be loaded via npm or downloaded from this repo.
There's also the possibility to directly import it via a CDN like jsdelivr or unpkg or similar.
$ npm install i18next-http-backend
Wiring up:
import i18next from 'i18next';
import HttpApi from 'i18next-http-backend';
i18next.use(HttpApi).init(i18nextOptions);
for Deno:
import i18next from 'https://deno.land/x/i18next/index.js'
import Backend from 'https://deno.land/x/i18next_http_backend/index.js'
i18next.use(Backend).init(i18nextOptions);
for plain browser:
<script src="https://cdn.jsdelivr.net/npm/i18next-http-backend@1.3.1/i18nextHttpBackend.min.js"></script>
i18next.use(i18nextHttpBackend).init(i18nextOptions);
- As with all modules you can either pass the constructor function (class) to the i18next.use or a concrete instance.
- If you don't use a module loader it will be added to
window.i18nextHttpBackend
Backend Options
{
loadPath: '/locales/{{lng}}/{{ns}}.json',
addPath: '/locales/add/{{lng}}/{{ns}}',
parse: function(data) { return data.replace(/a/g, ''); },
parsePayload: function(namespace, key, fallbackValue) { return { key: fallbackValue || "" } },
parseLoadPayload: function(languages, namespaces) { return undefined },
crossDomain: false,
withCredentials: false,
overrideMimeType: false,
customHeaders: {
authorization: 'foo',
},
customHeaders: () => ({
authorization: 'foo',
}),
requestOptions: {
mode: 'cors',
credentials: 'same-origin',
cache: 'default'
},
request: function (options, url, payload, callback) {},
queryStringParams: { v: '1.3.5' },
reloadInterval: false
}
Options can be passed in:
preferred - by setting options.backend in i18next.init:
import i18next from 'i18next';
import HttpApi from 'i18next-http-backend';
i18next.use(HttpApi).init({
backend: options,
});
on construction:
import HttpApi from 'i18next-http-backend';
const HttpApi = new HttpApi(null, options);
via calling init:
import HttpApi from 'i18next-http-backend';
const HttpApi = new HttpApi();
HttpApi.init(null, options);
TypeScript
To properly type the backend options, you can import the HttpBackendOptions
interface and use it as a generic type parameter to the i18next's init
method, e.g.:
import i18n from 'i18next'
import HttpBackend, { HttpBackendOptions } from 'i18next-http-backend'
i18n
.use(HttpBackend)
.init<HttpBackendOptions>({
backend: {
},
})
From the creators of i18next: localization as a service - locize.com
A translation management system built around the i18next ecosystem - locize.com.
With using locize you directly support the future of i18next.