API
Reference for the i18next API: init, use, t, exists, changeLanguage, loadNamespaces, addResourceBundle, events and the other instance methods.
init
i18next.init(options, callback) // -> returns a Promise
The default export of the i18next module is an i18next instance ready to be initialized by calling init. You can create additional instances using the createInstance function.
Please read the options page for details on configuration options.
The callback will be called after all translations were loaded or with an error when failed (in case of using a backend).
So you should wait for init to complete (wait for the callback or promise resolution) before using the t function!
i18next.init({
fallbackLng: 'en',
ns: ['file1', 'file2'],
defaultNS: 'file1',
debug: true
}, (err, t) => {
if (err) return console.log('something went wrong loading', err);
t('key'); // -> same as i18next.t
});
// with only callback
i18next.init((err, t) => {
if (err) return console.log('something went wrong loading', err);
t('key'); // -> same as i18next.t
});
// using Promises
i18next
.init({ /* options */ })
.then(function(t) { t('key'); });i18next.init({
fallbackLng: 'en',
ns: ['file1', 'file2'],
defaultNS: 'file1',
debug: true
}, (err, t) => {
if (err) return console.log('something went wrong loading', err);
t($ => $.key); // -> same as i18next.t
});
// with only callback
i18next.init((err, t) => {
if (err) return console.log('something went wrong loading', err);
t($ => $.key); // -> same as i18next.t
});
// using Promises
i18next
.init({ /* options */ })
.then(function(t) { t($ => $.key); });use
i18next.use(module)
The use function is there to load additional plugins to i18next.
For available module see the plugins page and don't forget to read the documentation of the plugin.
t
i18next.t(keys, options)
Please have a look at the translation functions like interpolation, formatting and plurals for more details on using it.
You can specify either one key as a String or multiple keys as an Array of String. The first one that resolves will be returned.
You can select the key you want using a selector function ($ => $.my.key). Keys will auto-complete automatically.
If you want to set a default value, use the defaultValue option:
exists
i18next.exists(key, options)
Uses the same resolve functionality as the t function and returns true if a key exists.
getFixedT
i18next.getFixedT(lng, ns, keyPrefix, fixedOpts?)
Returns a t function that defaults to given language or namespace.
All arguments can be optional/null.
lng and ns params could be arrays of languages or namespaces and will be treated as fallbacks in that case.
The optional keyPrefix will be automatically applied to the returned t function. i.e.
The optional fixedOpts.scopeNs (added in v26.0.10) carries a namespace list that the selector API uses to detect when a path's first segment is a namespace prefix — without affecting resolution scope. This is what react-i18next's useTranslation([nsA, nsB]) passes through so that t($ => $.nsB.foo) correctly routes to nsB, while plain t('foo') lookups stay isolated to the primary ns. Set it to the same array you would pass to useTranslation.
On the returned function you can like in the t function override the languages or namespaces by passing them in options or by prepending namespace.
changeLanguage
i18next.changeLanguage(lng, callback) // -> returns a Promise
Changes the language. The callback will be called as soon translations were loaded or an error occurs while loading.
Calling changeLanguage without lng uses the language detector to choose the language to set.
HINT: For easy testing—setting lng to 'cimode' will cause the t function to always return the key.
language
i18next.language
Is set to the current detected or set language.
If you need the primary used language depending on your configuration (supportedLngs, load) you will prefer using i18next.resolvedLanguage or i18next.languages[0].
languages
i18next.languages
Is set to an array of language codes that will be used to look up the translation value.
When the language is set, this array is populated with the new language codes. Unless overridden, this array is populated with less-specific versions of that code for fallback purposes, followed by the list of fallback languages.
resolvedLanguage
i18next.resolvedLanguage
Is set to the current resolved language. It can be used as primary used language, for example in a language switcher.
(introduced in v21.0.0)
hasLoadedNamespace
i18next.hasLoadedNamespace(ns, options) // -> returns true or false
Checks if namespace has loaded yet. i.e. used by react-i18next
loadNamespaces
i18next.loadNamespaces(ns, callback) // -> returns a Promise
Loads additional namespaces not defined in init options.
loadLanguages
i18next.loadLanguages(lngs, callback) // -> returns a Promise
Loads additional languages not defined in init options (preload).
reloadResources
i18next.reloadResources() // -> returns a Promise
Reloads resources on given state. Optionally you can pass an array of languages and namespaces as params if you don't want to reload all.
Without languages it reloads the current languages and every language the backend loaded or tried to load, also for clones of the instance (since v26.7.1; before, only the current languages), and it retries the bundles that failed to load.
hydrate
i18next.hydrate(resources, lng) // -> returns the instance
Puts resources rendered on the server into the store and changes to the server's language, each only the first time (since v26.7.0). For SSR integrations like react-i18next's useSSR; call it after init(). On a clone it does nothing, as a clone shares its parent's store. It sets initializedStoreOnce and initializedLanguageOnce, which such integrations used to set themselves.
setDefaultNamespace
i18next.setDefaultNamespace(ns)
Changes the default namespace.
dir
i18next.dir(lng)
Returns rtl or ltr depending on languages read direction. Without a language (before init(), or none resolved) it returns ltr (since v26.7.0; rtl before).
format
i18next.format(data, format, lng)
introduced in v8.4.0 (not recommended anymore)
Exposes the Formatter's format function. Starting with v26.0.0, this will always be backed by the built-in Formatter (or a custom Formatter module provided via .use()).
For formatting used in translation files checkout the formatting doc.
instance creation
createInstance
i18next.createInstance(options, callback)
Will return a new i18next instance.
Please read the options page for details on configuration options.
Providing a callback will automatically call init. Without a callback, call init() yourself; since v27 the options passed here are merged with the defaults right away, so instance.options and getFixedT() work before init() (t() returns '' until then). The new instance has its own logger and post-processors: it does not see what the default i18next instance registered with use().
The callback will be called after all translations were loaded or with an error when failed (in case of using a backend).
cloneInstance
i18next.cloneInstance(options)
Creates a clone of the current instance. Shares store, plugins and initial configuration. Can be used to create an instance sharing storage but being independent on set language or default namespaces.
A clone logs through its parent's logger (or a copy, if you pass debug or prefix) and uses its parent's post-processors, also those the parent registers later; post-processors registered on the clone stay its own (since v27, when logger and post-processors became per instance).
Since v26.4.7 the clone does not inherit preload: the parent already loaded those languages into the shared store, so the clone only loads its own language (and fallbacks). Pass preload in the options if the clone should load them too.
forkResourceStore
By setting the forkResourceStore option to true, it will not shares the store.
events
onInitialized
i18next.on('initialized', function(options) {})
Gets fired after initialization.
onLanguageChanged
i18next.on('languageChanged', function(lng) {})
Gets fired when changeLanguage got called.
onLoaded
i18next.on('loaded', function(loaded) {})
Gets fired on loaded resources.
onFailedLoading
i18next.on('failedLoading', function(lng, ns, msg) {})
Gets fired if loading resources failed (after the in-built retry algorithm).
onMissingKey
i18next.on('missingKey', function(lngs, namespace, key, res) {})
Gets fired on accessing a key not existing. Needs saveMissing set to true.
store events
Please be aware the i18next.store is only available on i18next after the init call.
onAdded
i18next.store.on('added', function(lng, ns) {})
Gets fired when resources got added.
onRemoved
i18next.store.on('removed', function(lng, ns) {})
Gets fired when resources got removed.
resource handling
Can be accessed on i18next or i18next.services.resourceStore.
getResource
i18next.getResource(lng, ns, key, options)
Gets one value by given key.
options:
keySeparator
"."
char to separate keys, or false if no separator is preferred
ignoreJSONStructure
true
if a key is not found as nested key, it will try to lookup as flat key
addResource
i18next.addResource(lng, ns, key, value, options)
Adds one key/value.
options:
keySeparator
"."
char to separate keys, or false if no separator is preferred
silent
false
if set to true adding will not emit an added event
addResources
i18next.addResources(lng, ns, resources)
Adds multiple key/values.
addResourceBundle
i18next.addResourceBundle(lng, ns, resources, deep, overwrite)
Adds a complete bundle.
Setting deep (default false) param to true will extend existing translations in that file. Setting deep and overwrite (default false) to true it will overwrite existing translations in that file.
So omitting deep and overwrite will overwrite all existing translations with the one provided in resources. Using deep you can choose to keep existing nested translation and to overwrite those with the new ones.
hasResourceBundle
i18next.hasResourceBundle(lng, ns)
Checks if a resource bundle exists.
getDataByLanguage
i18next.getDataByLanguage(lng)
Returns a resource data by language.
getResourceBundle
i18next.getResourceBundle(lng, ns)
Returns a resource bundle.
removeResourceBundle
i18next.removeResourceBundle(lng, ns)
Removes an existing bundle.
Last updated