Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

i18next-browser-languagedetector

i18next8.1mMIT8.0.4TypeScript support: included

language detector used in browser environment for i18next

i18next, i18next-languageDetector

readme

Introduction

npm version

This is an i18next language detection plugin used to detect user language in the browser, with support for:

  • cookie (set cookie i18next=LANGUAGE)
  • sessionStorage (set key i18nextLng=LANGUAGE)
  • localStorage (set key i18nextLng=LANGUAGE)
  • navigator (set browser language)
  • querystring (append ?lng=LANGUAGE to URL)
  • htmlTag (add html language tag <html lang="LANGUAGE" ...)
  • path (http://my.site.com/LANGUAGE/...)
  • subdomain (http://LANGUAGE.site.com/...)

Getting started

Source can be loaded via npm, bower or downloaded from this repo.

# npm package
$ npm install i18next-browser-languagedetector

# bower
$ bower install i18next-browser-languagedetector
  • If you don't use a module loader it will be added to window.i18nextBrowserLanguageDetector

Wiring up:

import i18next from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

i18next.use(LanguageDetector).init({
  supportedLngs: ['de', 'en', 'fr'],
  ...i18nextOptions
});

As with all modules you can either pass the constructor function (class) to the i18next.use or to a concrete instance.

supportedLngs is optional, but allows i18next to pick the best match from the list of detected languages. If it's not set then language will be set to the first detected language, regardless of whether your application has translations for that language or not.

Detector Options

The default options can be found here.

{
  // order and from where user language should be detected
  order: ['querystring', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag', 'path', 'subdomain'],

  // keys or params to lookup language from
  lookupQuerystring: 'lng',
  lookupCookie: 'i18next',
  lookupLocalStorage: 'i18nextLng',
  lookupSessionStorage: 'i18nextLng',
  lookupFromPathIndex: 0,
  lookupFromSubdomainIndex: 0,

  // cache user language on
  caches: ['localStorage', 'cookie'],
  excludeCacheFor: ['cimode'], // languages to not persist (cookie, localStorage)

  // optional expiry and domain for set cookie
  cookieMinutes: 10,
  cookieDomain: 'myDomain',

  // optional htmlTag with lang attribute, the default is:
  htmlTag: document.documentElement,

  // optional set cookie options, reference:[MDN Set-Cookie docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)
  cookieOptions: { path: '/', sameSite: 'strict' },

  // optional conversion function used to modify the detected language code
  convertDetectedLanguage: 'Iso15897',
  convertDetectedLanguage: (lng) => lng.replace('-', '_')
}

Options can be passed in:

preferred - by setting options.detection in i18next.init:

import i18next from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

i18next.use(LanguageDetector).init({
  detection: options,
});

on construction:

import LanguageDetector from 'i18next-browser-languagedetector';
const languageDetector = new LanguageDetector(null, options);

via calling init:

import LanguageDetector from 'i18next-browser-languagedetector';
const languageDetector = new LanguageDetector();
languageDetector.init(options);

Adding own detection functionality

interface

export default {
  name: 'myDetectorsName',

  lookup(options) {
    // options -> are passed in options
    return 'en';
  },

  cacheUserLanguage(lng, options) {
    // options -> are passed in options
    // lng -> current language, will be called after init and on changeLanguage
    // store it
  },
};

adding it

import LanguageDetector from 'i18next-browser-languagedetector';
const languageDetector = new LanguageDetector();
languageDetector.addDetector(myDetector);

i18next.use(languageDetector).init({
  detection: options,
});

Don't forget: You have to add the name of your detector (myDetectorsName in this case) to the order array in your options object. Without that, your detector won't be used. See the Detector Options section for more.


Gold Sponsors


localization as a service - locize.com

Needing a translation management? Want to edit your translations with an InContext Editor? Use the orginal provided to you by the maintainers of i18next!

locize

With using locize you directly support the future of i18next and react-i18next.


changelog

8.0.4

  • fix localstorage check to try to address 297 300

8.0.3

  • change localstorage check to try to address 297

8.0.2

  • fix for when passed services are null, should address 296

8.0.1

  • some environments, throws when accessing document.cookie

8.0.0

  • chore: set browsers target to defaults 286
  • perf: use object deconstruction, optional chaining and hot path optimisations 287

7.2.1

  • fix: align addDetector impementation to type definition 282

7.2.0

  • fix: separate cjs and mjs typings

7.1.0

  • introduce convertDetectedLanguage option

7.0.2

  • simplify usage without i18next

7.0.1

  • try to force esm moduel type for esm build 269

7.0.0

  • typescript fix for i18next v22

6.1.8

  • fix export order for typescript 267

6.1.7

  • Types entries missing in package exports (Needed for Typescript >= 4.7 and moduleResolution="Node16"/"Nodenext") 266

6.1.6

  • define module exports in package.json

6.1.5

  • lookup subdomain with localhost option 264

6.1.4

  • fix querystring lookup if happening after # 256

6.1.3

  • export DecetorOptions and CustomDetector types

6.1.2

  • fix lookup return types 245

6.1.1

  • cookieOptions types 239

6.1.0

  • Type PluginOptions properly 235

6.0.1

  • optimize check for local storage and session storage 222

6.0.0

  • BREAKING rename lookupSessionStorage and add it to defaults 221

5.0.1

  • optimize cookie serialization and set sameSite to strict by default, to prepare for browser changes

5.0.0

  • BREAKING needs i18next >= 19.5.0
  • let i18next figure out which detected lng is best match

4.3.1

  • typescript Updated typescript typings for DetectorOptions to align with current options 216

4.3.0

  • sessionStorage support 215

4.2.0

  • Add config option checkForSimilarInWhitelist 211

4.1.1

  • fix: pass cookieOptions with the cacheUserLang 205

4.1.0

  • feat: add cookieOptions for setting cookies 203

4.0.2

  • update index file to reflect build changes done in 4.0.0

4.0.1

  • typescript: Use updated ts export default from i18next 194

4.0.0

  • removes deprecated jsnext:main from package.json
  • Bundle all entry points with rollup bringing it up to same standard as xhr-backend
  • note: dist/es -> dist/esm, dist/commonjs -> dist/cjs (individual files -> one bundled file)
  • removes bower finally

v3.1.1

  • add default checkWhitelist: true

v3.1.0

  • Added option to prevent checking whitelist for detected languages checkWhitelist: true 190

v3.0.3

  • Remove clutter from npm package 181

v3.0.2

  • typescript: Fix types for use() module 180

v3.0.1

  • typescript: fix types 165

v3.0.0

  • typescript: add types 164

v2.2.4

v2.2.3

v2.2.2

  • Lang by path: skip if language not found 159

v2.2.1

  • fixes option validation in path lookup 158
  • fixes lookup from href for subdomain 157

v2.2.0

  • add detector for path and subdomain PR153 and PR152

v2.1.1

  • support for fallback language in form of object 151

v2.1.0

  • add .js for browser import implementation PR147

v2.0.0

  • [BREAKING] options.excludeCacheFor (array of language codes; default ['cimode']): if a language maps a value in that list the language will not be written to cache (eg. localStorage, cookie). If you use lng cimode in your tests and require it to be cached set the option to false or empty array