• Stars
    star
    434
  • Rank 100,274 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

i18next-http-backend is a backend layer for i18next using in Node.js, in the browser and for Deno.

Introduction

Actions Actions deno Travis npm version

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',
  // other options
})

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 package
$ 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/[email protected]/i18nextHttpBackend.min.js"></script>
<!-- an example can be found in example/jquery/index.html -->
  • 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

{
  // path where resources get loaded from, or a function
  // returning a path:
  // function(lngs, namespaces) { return customPath; }
  // the returned path will interpolate lng, ns if provided like giving a static path
  // the function might return a promise
  // returning falsy will abort the download
  //
  // If not used with i18next-multiload-backend-adapter, lngs and namespaces will have only one element each,
  // If used with i18next-multiload-backend-adapter, lngs and namespaces can have multiple elements
  //   and also your server needs to support multiloading
  //      /locales/resources.json?lng=de+en&ns=ns1+ns2
  //   Adapter is needed to enable MultiLoading https://github.com/i18next/i18next-multiload-backend-adapter
  //   Returned JSON structure in this case is
  //   {
  //    lang : {
  //     namespaceA: {},
  //     namespaceB: {},
  //     ...etc
  //    }
  //   }
  loadPath: '/locales/{{lng}}/{{ns}}.json',

  // path to post missing resources, or a function
  // function(lng, namespace) { return customPath; }
  // the returned path will interpolate lng, ns if provided like giving a static path
  addPath: '/locales/add/{{lng}}/{{ns}}',

  // parse data after it has been fetched
  // in example use https://www.npmjs.com/package/json5
  // here it removes the letter a from the json (bad idea)
  parse: function(data) { return data.replace(/a/g, ''); },

  // parse data before it has been sent by addPath
  parsePayload: function(namespace, key, fallbackValue) { return { key: fallbackValue || "" } },

  // parse data before it has been sent by loadPath
  // if value returned it will send a POST request
  parseLoadPayload: function(languages, namespaces) { return undefined },

  // allow cross domain requests
  crossDomain: false,

  // allow credentials on cross domain requests
  withCredentials: false,

  // overrideMimeType sets request.overrideMimeType("application/json")
  overrideMimeType: false,

  // custom request headers sets request.setRequestHeader(key, value)
  customHeaders: {
    authorization: 'foo',
    // ...
  },
  // can also be a function, that returns the headers
  customHeaders: () => ({
    authorization: 'foo',
    // ...
  }),

  requestOptions: { // used for fetch, can also be a function (payload) => ({ method: 'GET' })
    mode: 'cors',
    credentials: 'same-origin',
    cache: 'default'
  }

  // define a custom request function
  // can be used to support XDomainRequest in IE 8 and 9
  //
  // 'options' will be this entire options object
  // 'url' will be passed the value of 'loadPath'
  // 'payload' will be a key:value object used when saving missing translations
  // 'callback' is a function that takes two parameters, 'err' and 'res'.
  //            'err' should be an error
  //            'res' should be an object with a 'status' property and a 'data' property containing a stringified object instance beeing the key:value translation pairs for the
  //            requested language and namespace, or null in case of an error.
  request: function (options, url, payload, callback) {},

  // adds parameters to resource URL. 'example.com' -> 'example.com?v=1.3.5'
  queryStringParams: { v: '1.3.5' },

  reloadInterval: false // can be used to reload resources in a specific interval (milliseconds) (useful in server environments)
}

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: {
      // http backend options
    },

    // other i18next options
  })

Gold Sponsors


From the creators of i18next: localization as a service - locize.com

A translation management system built around the i18next ecosystem - locize.com.

locize

With using locize you directly support the future of i18next.


More Repositories

1

react-i18next

Internationalization for react done right. Using the i18next i18n ecosystem.
JavaScript
9,188
star
2

i18next

i18next: learn once - translate everywhere
JavaScript
7,594
star
3

next-i18next

The easiest way to translate your NextJs apps.
TypeScript
5,429
star
4

i18next-browser-languageDetector

language detector used in browser environment for i18next
JavaScript
842
star
5

i18next-scanner

Scan your code, extract translation keys/values, and merge them into i18n resource files.
JavaScript
554
star
6

i18next-parser

Parse your code to extract translation keys/values and manage your catalog files
JavaScript
468
star
7

i18next-node

[deprecated] can be replaced with v2 of i18next
JavaScript
261
star
8

i18next-xhr-backend

[deprecated] can be replaced with i18next-http-backend
JavaScript
254
star
9

i18next-express-middleware

[deprecated] can be replaced with i18next-http-middleware
JavaScript
207
star
10

i18next-gettext-converter

converts gettext .mo or .po to 18next json format and vice versa
JavaScript
193
star
11

next-app-dir-i18next-example

Next.js 13/14 app directory feature in combination with i18next
JavaScript
169
star
12

jquery-i18next

jQuery-i18next is a jQuery based Javascript internationalization library on top of i18next. It helps you to easily internationalize your web applications.
HTML
168
star
13

i18next-gitbook

HTML
163
star
14

ng-i18next

translation for AngularJS using i18next
JavaScript
161
star
15

i18next-http-middleware

i18next-http-middleware is a middleware to be used with Node.js web frameworks like express or Fastify and also for Deno.
JavaScript
148
star
16

next-app-dir-i18next-example-ts

Next.js 13/14 app directory feature in combination with i18next
TypeScript
105
star
17

react-i18next-gitbook

CSS
95
star
18

i18next-fs-backend

i18next-fs-backend is a backend layer for i18next using in Node.js and for Deno to load translations from the filesystem.
JavaScript
92
star
19

i18next-localstorage-backend

This is a i18next cache layer to be used in the browser. It will load and cache resources from localStorage and can be used in combination with the chained backend.
JavaScript
83
star
20

i18next-icu

i18nFormat plugin to use ICU format with i18next
JavaScript
79
star
21

i18next-vue

Internationalization for Vue 2 & 3 using the i18next ecosystem
TypeScript
70
star
22

i18next-node-fs-backend

[deprecated] can be replaced with i18next-fs-backend
JavaScript
65
star
23

i18next-chained-backend

An i18next backend to chain multiple backends (add fallbacks, caches, ...)
JavaScript
64
star
24

i18nextify

enables localization of any page with zero effort.
JavaScript
61
star
25

next-language-detector

This package helps to handle language detection in next.js when using static servers only.
JavaScript
57
star
26

i18next-resources-to-backend

This package helps to transform resources to an i18next backend
JavaScript
53
star
27

i18next-android

i18next internationalization library for Android
Java
42
star
28

i18next-webtranslate

[deprecated] Translation User Interface for i18next - successor locize.com
JavaScript
41
star
29

i18next-resources-for-ts

This package helps to transform resources to be used in a typesafe i18next project.
JavaScript
31
star
30

i18next-ios

i18next internationalization library for iOS
Objective-C
29
star
31

i18next-sprintf-postProcessor

sprintf post processor for i18next
JavaScript
28
star
32

i18next-localStorage-cache

[deprecated] caching layer for i18next using browsers localStorage
JavaScript
25
star
33

i18next-intervalPlural-postProcessor

post processor for i18next enabling interval plurals
JavaScript
25
star
34

i18next-fluent

i18nFormat plugin to use mozilla fluent format with i18next
JavaScript
22
star
35

i18next-multiload-backend-adapter

This is a i18next backend to enable another backend's multiload behaviour of loading multiple lng-ns combinations with one request.
JavaScript
16
star
36

next-app-dir-i18next-no-locale-path-example

JavaScript
15
star
37

i18next-emoji-postprocessor

This is a postProcessor plugin for i18next using in Node.js and in the browser that replaces all words with emojis.
JavaScript
10
star
38

i18next-v4-format-converter

This package helps to convert old i18next translation resources to the new i18next v4 json format.
JavaScript
9
star
39

i18next.com

[obsolete] was replaced by i18next-gitbook! i18next.com website
JavaScript
7
star
40

grunt-i18next

Bundle language resource files for i18next.
JavaScript
6
star
41

i18next-translation-parser

parses i18next translations to AST
JavaScript
6
star
42

i18next-node-remote-backend

[deprecated] can be replaced with i18next-http-backend
JavaScript
6
star
43

omi-i18n

omi-i18n solution for omi.js using i18next ecosystem
JavaScript
5
star
44

i18next-fluent-backend

i18next backend to load fluent formatted .ftl files via xhr
JavaScript
4
star
45

i18next-polyglot

i18nFormat plugin to use airbnb/polyglot.js format with i18next
JavaScript
4
star
46

i18next-cli-app-example

i18next in a cli app
JavaScript
2
star
47

bs-react-i18next

Bucklescript + ReasonReact binding for react-i18next components.
OCaml
1
star