Initialization
var i18n = require("i18next");
i18n.init();// with options
i18n.init({ lng: "en-US" });
// "later"
var x = i18n.t("key");
// with callback
i18n.init(function(err, t) {
var x = t("key");
});
// with both
i18n.init({ lng: "en-US" }, function(err, t) {
var x = t("key");
});Basic Options
Set language on init:
i18n.init({ lng: 'en-US' });Resources will be resolved in this order:
- 1) try languageCode plus countryCode, eg. 'en-US'
- 2) alternative look it up in languageCode only, eg. 'en'
- 3) finally look it up in definded fallback language, default: 'dev'
Change language programatically:
Call functioni18n.setLng(lng, callback).Read out current language:
Call functioni18n.lng() returns current lng.Set language after init:
i18n.setLng('en-US', function(err, t) { /* loading done */ });you could fix the language by calling it this way:
i18n.setLng('en-US', { fixLng: true }, function(enUS) { /* done */ });
every call to enUS ( enUS(key, opts) ) will return in enUS even if setLng is called again in different lng
If language is not set explicitly i18next tries to detect the user language by:
- 1) querystring parameter (?setLng=en-US)
- 2) cookie (i18next)
- 3) request header
Turn cookie off:
Call functioni18n.init({ useCookie: false }).Don't lookup in header:
Call functioni18n.init({ detectLngFromHeaders: false }).Detect from route:
Alternatively you can init i18next to set language from requested route:
i18n.init({ detectLngFromPath: 0 }); // default falseJust set the value to the index where the language value is, eg.:
- detectLngFromPath = 0 --> /en-US/myPage
- detectLngFromPath = 1 --> /cms/en-US/anotherPage
Hint: to set i18next to set language to fallbackLng if no locale could be set by path you could set init option 'forceDetectLngFromPath' to true. This will stop any further lookup via querystring or cookie.
Control over supported languages:
To avoid i18next returning unsupported languages you could set an array of
supported languages on init:i18n.init({supportedLngs: ['en', 'de']}).Change the querystring param to lookup lng:
i18n.init({ detectLngQS: 'lang' });The current locale to set will be looked up in the new parameter: ?lang=en-US
Change the cookie name to lookup lng:
i18n.init({ cookieName: 'lang' }); /* default 'i18next' */The current locale to set and looked up in the given cookie parameter.
Change the cookie domain:
i18n.init({ cookieDomain: '*.mydomain.com' });Sets the cookie domain to given value.
Disable cookie usage:
i18n.init({ useCookie: false });Use this only if your sure that language will be provided by the other lookup options or set programatically.
preload additional languages on init:
i18n.init({ preload: ['de-DE', 'fr'] });The additional languages will be preloaded.
Preload after init:
Call function i18n.preload([lngs], callback).Unset/Set fallback language:
setting one or multiple fallback language:
i18n.init({ fallbackLng: 'en' });
// or
i18n.init({ fallbackLng: ['fr', 'en'] });If not set it will default to 'dev'. If turned on, all missing key/values will be sent to this language.
Production Hint: set fallback language to some meaningful language, eg. 'en'
turn fallback language feature off:
i18n.init({ fallbackLng: false });As the fallbackLng will default to 'dev' you can turn it off by setting the option value to false. This will prevent loading the fallbacks resource file and any futher look up of missing value inside a fallback file.
Specify which locales to load:
This will help you optimizing the loading behaviour. In combination with setting fallbackLng to false you can reduce the requests to the server to one!
only load current resource file:
i18n.init({ load: 'current' });If load option is set to current i18next will load the current set language (this could be a specific (en-US) or unspecific (en) resource file).
Hint: to prevent loading the fallbackLng's resource file set fallbackLng to false.
only load unspecific resource file:
i18n.init({ load: 'unspecific' });If set to unspecific i18next will always load the unspecific resource file (eg. en instead of en-US).
Hint: to prevent loading the fallbackLng's resource file set fallbackLng to false.
Debug output:
i18n.init({ debug: true });If something went wrong you might find some helpful information on console log.
Resource Loading
init callback when loaded
i18n.init(callback);i18n.init(function(err, t) {
var appName = t("key");
});after callback is called you can use the translation function 't' to access your resources in given language.
options to load resources
Pass in resource store:
// tree: lng -> namespace -> key -> nested key
var resources = {
dev: { translation: { 'key': 'value' } },
en: { translation: { 'key': 'value' } },
'en-US': { translation: { 'key': 'value' } }
};
i18n.init({ resStore: resources });As you provide the resources the callbacks will fire immediatly and no external resources will be loaded!
Set filepath to load resources from:
var option = { resGetPath: 'locales/__lng__/__ns__.json' };
i18n.init(option);Will load 'locales/en-US/translation.json'.
If language is set to 'en-US' following resource files will be loaded one-by-one:
- en-US
- en
- dev (default fallback language)
Hint: to lowercase countryCode in requests, eg. to 'en-us' set option lowerCaseLng = true
var option = { resGetPath: 'locales/__ns__-__lng__.json' };
i18n.init(option);Will load 'locales/translation-en-US.json'.
Change namespace (one):
var option = { ns: 'resource' };
i18n.init(option);Will load:
- 'locales/en-US/resource.json'
- 'locales/en/resource.json'
- 'locales/dev/resource.json'
(Default namespace is 'translation'.)
Multiple namespace:
var option = {
ns: {
namespaces: ['app', 'buttons'],
defaultNs: 'app'
}
};
i18n.init(option, function(err, t) {
// access default namespace
var x = t("any.key.from.app")
// to access another namespace prepend [ns]:
var y = t("buttons:any.key.from.buttons")
});Will load:
- 'locales/en-US/app.json'
- 'locales/en/app.json'
- 'locales/dev/app.json'
- 'locales/en-US/buttons.json'
- 'locales/en/buttons.json'
- 'locales/dev/buttons.json'
Change Backend Implementation
Change out backend:
default is filesystem
Options are:
- mongoDb
- redis
- couchDb
- gettext
mongoDb:
npm install i18next.mongoDb
var i18nextMongoSync = require('i18next.mongoDb')
i18nextMongoSync.connect({
host: "localhost",
port: 27017,
dbName: "i18next"
/*
resCollectionName: "resources",
username: "usr",
password: "pwd",
options: {
auto_reconnect: true, // default true
ssl: false // default false
}
*/
}, function() {
i18n.backend(i18nMongoSync);
i18n.init();
});redis:
npm install i18next.redis
var i18nextRedisSync = require('i18next.redis')
i18nextRedisSync.connect({
host: "localhost",
port: 27017,
database: 0
// resCollectionName: "resources",
}, function() {
i18n.backend(i18nRedisSync);
i18n.init();
});couchDb:
npm install i18next.couchdb
var i18nextCouchSync = require('i18next.couchdb')
i18nextCouchSync.connect({
host: "http://localhost",
port: 5984,
dbName: "i18next"
/*
resCollectionName: "resources",
options: {
cache: true, // default true
raw: false, // default false
secure: true, // default false
auth: { username: 'usr', password: 'pwd' } // default none
}
*/
}, function() {
i18n.backend(i18nextCouchSync);
i18n.init();
});additional backend functions
// loading loadResourceSet(lng, ns, cb)
backend.fetchOne("en-US," "myNamespace", function(err, resourceSet) { ... });
// saving saveResourceSet(lng, ns, resouceSet, cb)
var myResourceSet = {...};
backend.saveResourceSet("en-US", "myNamespace", myResourceSet, function(err) {
// handle err
});The additional database backends where provided thanks to adrai.
npm install i18next.remotesync
var remoteSync = require('i18next.remotesync')
i18n.backend(remoteSync);
i18n.init({
resGetPath: 'http://myServer.com/locales/__lng__/__ns__.json',
resPostPath: 'http://myServer.com/locales/add/__lng__/__ns__'
// resUpdatePath: 'http://myServer.com/locales/update/__lng__/__ns__',
// resREmovePath: 'http://myServer.com/locales/remove/__lng__/__ns__'
});remote sync just uses request to get or set resources from a remote location.
npm install i18next.gettext
var gettextSync = require('i18next.gettext')
i18n.backend(gettextSync);
i18n.init({ resGetPath: 'locales/__lng__/__ns__.mo' }); // or .pogettext-sync only supports loading resources! Saving of missing resources is not yet supported.
Tips:
namespaces:
alternatively to prepending namespacei18n.t('messages:login failed!') you could pass it via options i18n.t('login failed!', { ns: 'messages' }).defining different separators
as '.' and ':' might be part of the key (eg.i18n.t('this will break. because of the dot') ) you could change the separators, like:i18n.init({
keyseparator: '::',
nsseparator: ':::'
});to prevent issues.npm install i18next.yaml
var yamlSync = require('i18next.yaml')
i18n.backend(yamlSync);
i18n.init({ resGetPath: 'locales/__lng__/__ns__.yml' }); // or .yamlyaml-sync only supports loading resources! Saving of missing resources is not yet supported.
Tips:
namespaces:
alternatively to prepending namespacei18n.t('messages:login failed!') you could pass it via options i18n.t('login failed!', { ns: 'messages' }).defining different separators
as '.' and ':' might be part of the key (eg.i18n.t('this will break. because of the dot') ) you could change the separators, like:i18n.init({
keyseparator: '::',
nsseparator: ':::'
});to prevent issues.