npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

i18next-http-backend

v3.0.1

Published

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

Downloads

4,759,392

Readme

Introduction

Actions Actions deno 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 -->
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

{
  // 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
  //
  // note that this only works when initialized with { saveMissing: true }
  // (see https://www.i18next.com/overview/configuration-options)
  addPath: '/locales/add/{{lng}}/{{ns}}',

  // parse data after it has been fetched
  // in example use https://www.npmjs.com/package/json5 or https://www.npmjs.com/package/jsonc-parser
  // 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
  })


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.