### Dynamic Documentation Query Example Source: https://www.i18next.com/how-to/backend-fallback Demonstrates how to query documentation dynamically using an HTTP GET request with the `ask` query parameter. ```http GET https://www.i18next.com/how-to/backend-fallback.md?ask= ``` -------------------------------- ### Initialize i18next with Basic Translations (TypeScript) Source: https://www.i18next.com/overview/comparison-to-others This TypeScript example demonstrates initializing i18next with a default language and basic translations. It's useful for projects already using TypeScript and requiring straightforward internationalization setup. ```typescript import i18next from 'i18next'; i18next.init({ lng: 'de', resources: { de: { translation: { "hello world": "hallo Welt" } } } }); i18next.t($ => $['hello world']); // hallo Welt ``` -------------------------------- ### Query Documentation via GET Request Source: https://www.i18next.com/misc/creating-own-plugins Use a GET request with the 'ask' query parameter to dynamically query documentation content. This is useful for retrieving specific information or clarifications not explicitly present on the page. ```http GET https://www.i18next.com/misc/creating-own-plugins.md?ask= ``` -------------------------------- ### Namespace Examples Source: https://www.i18next.com/principles/translation-resolution Provides examples of common namespaces used for organizing translation keys, such as 'common', 'validation', and 'glossary'. ```plaintext "common" // Things that are reused everywhere, like "Confirm" and "Cancel" on buttons "validation" // All validation text, like "email address not valid" in a form "glossary" // Words we want to be reused consistently, like key words in your app ``` -------------------------------- ### Querying Documentation with `ask` Parameter Source: https://www.i18next.com/principles/fallback Demonstrates how to perform an HTTP GET request with the `ask` query parameter to dynamically query documentation. ```http GET https://www.i18next.com/principles/fallback.md?ask= ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://www.i18next.com/misc/json-format Perform an HTTP GET request on the current page URL with the `ask` query parameter to dynamically query the documentation. The question should be specific and in natural language. ```http GET https://www.i18next.com/misc/json-format.md?ask= ``` -------------------------------- ### Install Intl.PluralRules polyfill Source: https://www.i18next.com/how-to/faq Install the intl-pluralrules package to ensure Intl.PluralRules API compatibility in environments where it's not natively available. This is crucial for correct pluralization handling. ```shell npm install intl-pluralrules ``` -------------------------------- ### Query Documentation via GET Request Source: https://www.i18next.com/overview/configuration-options To get additional information not directly on the page, perform an HTTP GET request to the page URL with an 'ask' query parameter containing your question. ```http GET https://www.i18next.com/overview/configuration-options.md?ask= ``` -------------------------------- ### Perform HTTP GET Request with 'ask' Parameter Source: https://www.i18next.com/misc/the-history-of-i18next Use this method to query documentation dynamically. The question should be specific and in natural language. The response includes answers and relevant excerpts. ```http GET https://www.i18next.com/misc/the-history-of-i18next.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://www.i18next.com/how-to/extracting-translations To get additional information not explicitly present on the page, perform an HTTP GET request to the page URL with the `ask` query parameter. The question should be specific and self-contained. ```http GET https://www.i18next.com/how-to/extracting-translations.md?ask= ``` -------------------------------- ### Node.js Setup for i18next v2.0.0 Source: https://www.i18next.com/misc/migration-guide Configure i18next for Node.js environments using the filesystem backend and sprintf postprocessor. ```javascript var i18next = require('i18next'); FilesystemBackend = require('i18next-node-fs-backend'); sprintf = require('i18next-sprintf-postprocessor'); i18next .use(FilesystemBackend) .use(sprintf) .init(options, callback); ``` -------------------------------- ### Initialize i18next with Resources (JavaScript) Source: https://www.i18next.com/overview/getting-started Initializes i18next with English translation resources. Use this for basic setup where translation data is available upfront. ```javascript import i18next from 'i18next'; i18next.init({ lng: 'en', // if you're using a language detector, do not define the lng option debug: true, resources: { en: { translation: { "key": "hello world" } } } }); // initialized and ready to go! // i18next is already initialized, because the translation resources where passed via init function document.getElementById('output').innerHTML = i18next.t('key'); ``` -------------------------------- ### Initialize i18next with a Custom Backend Plugin Source: https://www.i18next.com/misc/creating-own-plugins Integrate a custom backend plugin into your i18next setup using the `.use()` method before calling `.init()`. Ensure the plugin is imported correctly. ```javascript import i18n from "i18next"; import { initReactI18next } from "react-i18next"; import i18nBackend from "my-custom-backend"; i18n .use(i18nBackend) .use(initReactI18next) .init({ backend: { // custom options }, // other options }); ``` -------------------------------- ### Server-Side Fallback with Filesystem Source: https://www.i18next.com/how-to/backend-fallback Configure i18next for server-side applications using `i18next-fs-backend` as a fallback. This example chains `HttpBackend` with `FsBackend`. ```javascript import i18next from "i18next"; import ChainedBackend from "i18next-chained-backend"; import HttpBackend from "i18next-http-backend"; import FsBackend from "i18next-fs-backend"; i18next .use(ChainedBackend) .init({ fallbackLng: "en", // ... your i18next config backend: { backends: [ HttpBackend, FsBackend ], backendOptions: [{ loadPath: '/locales/{{lng}}/{{ns}}.json' }, { loadPath: './locales_cache/{{lng}}/{{ns}}.json' }] } }); ``` -------------------------------- ### Query Documentation Dynamically Source: https://www.i18next.com/overview/typescript To get specific information not present on the page, perform an HTTP GET request to the current page URL with the `ask` query parameter. The question should be specific and in natural language. ```http GET https://www.i18next.com/overview/typescript.md?ask= ``` -------------------------------- ### Querying Documentation Dynamically Source: https://www.i18next.com/how-to/add-or-load-translations To get additional information not directly present on the page, perform an HTTP GET request to the current page URL with the 'ask' query parameter. The question should be specific and self-contained. ```http GET https://www.i18next.com/how-to/add-or-load-translations.md?ask= ``` -------------------------------- ### Querying Documentation via API Source: https://www.i18next.com/overview/first-setup-help To get information not directly on the page, make a GET request to the page URL with an 'ask' query parameter containing your question. ```http GET https://www.i18next.com/overview/first-setup-help.md?ask= ``` -------------------------------- ### Perform HTTP GET Request to Query Documentation Source: https://www.i18next.com/misc/migration-guide Use this method to ask questions about the documentation. The question should be specific and in natural language. The response will contain direct answers and relevant excerpts. ```http GET https://www.i18next.com/misc/migration-guide.md?ask= ``` -------------------------------- ### Install i18next with npm or yarn Source: https://www.i18next.com/overview/getting-started Use npm or yarn to add i18next to your project dependencies. ```bash # npm $ npm install i18next --save ``` ```bash # yarn $ yarn add i18next ``` -------------------------------- ### Perform HTTP GET Request to Query Documentation Source: https://www.i18next.com/overview/supported-frameworks Use this method to query documentation dynamically. The question should be specific and self-contained. The response includes a direct answer and relevant excerpts. ```http GET https://www.i18next.com/overview/supported-frameworks.md?ask= ``` -------------------------------- ### Querying Documentation Source: https://www.i18next.com/overview/api You can dynamically query the documentation by asking questions via a GET request with the 'ask' query parameter. ```APIDOC ## Querying This Documentation ### Description If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question. Perform an HTTP GET request on the current page URL with the `ask` query parameter. ### Method GET ### Endpoint `https://www.i18next.com/overview/api.md?ask=` ### Parameters #### Query Parameters - **ask** (string) - Required - Your specific, self-contained question in natural language. ### Usage The question should be specific, self-contained, and written in natural language. The response will contain a direct answer to the question and relevant excerpts and sources from the documentation. Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections. ``` -------------------------------- ### Query i18next Documentation Dynamically Source: https://www.i18next.com/how-to/faq To get additional information not directly available on a page, perform an HTTP GET request to the page URL with the 'ask' query parameter. The question should be specific and in natural language. ```http GET https://www.i18next.com/how-to/faq.md?ask= ``` -------------------------------- ### Querying Documentation via API Source: https://www.i18next.com/translation-function/interpolation Perform an HTTP GET request to the documentation URL with an `ask` query parameter to dynamically query for information not explicitly present on the page. The response includes direct answers and relevant excerpts. ```http GET https://www.i18next.com/translation-function/interpolation.md?ask= ``` -------------------------------- ### Perform Dynamic Documentation Query Source: https://www.i18next.com/principles/translation-resolution To query the documentation dynamically, perform an HTTP GET request on the current page URL and include the 'ask' query parameter with your question. The question should be specific and self-contained. ```http GET https://www.i18next.com/principles/translation-resolution.md?ask= ``` -------------------------------- ### Node.js + Express Setup for i18next v2.0.0 Source: https://www.i18next.com/misc/migration-guide Set up i18next with Express.js, including language detection, filesystem backend, sprintf postprocessor, and middleware for handling requests and resources. ```javascript var express = require('express'); i18next = require('i18next'); FilesystemBackend = require('i18next-node-fs-backend'); sprintf = require('i18next-sprintf-postprocessor'); i18nextMiddleware = require('i18next-express-middleware'); i18next .use(i18nextMiddleware.LanguageDetector) .use(FilesystemBackend) .use(sprintf) .init(options, callback); var app = express(); app.use(i18nextMiddleware.handle(i18next)); // expose req.t with fixed lng app.post('/locales/add/:lng/:ns', i18nextMiddleware.missingKeyHandler(i18next)); // serves missing key route for consumers (browser) app.get('/locales/resources.json', i18nextMiddleware.getResourcesHandler(i18next)); // serves resources for consumers (browser) app.listen(3000); ``` -------------------------------- ### Load i18next Plugins Source: https://www.i18next.com/overview/api Use the 'use' function to load additional plugins into i18next. Ensure you have installed the desired plugins and read their specific documentation. ```javascript import i18next from 'i18next'; import Backend from 'i18next-http-backend'; import LocalStorageBackend from 'i18next-localstorage-backend'; // used with i18next-chained-backend for caching import postProcessor from 'i18next-sprintf-postprocessor'; import LanguageDetector from 'i18next-browser-languagedetector'; i18next .use(Backend) .use(LocalStorageBackend) .use(LanguageDetector) .use(postProcessor) .init(options, callback); ``` -------------------------------- ### Get Specific Resource Bundle Source: https://www.i18next.com/overview/api Retrieves a specific resource bundle for a given language and namespace from i18next. ```javascript i18next.getResourceBundle(lng, ns) ``` -------------------------------- ### Query Documentation via API Source: https://www.i18next.com/principles/plugins Shows how to dynamically query the i18next documentation by making an HTTP GET request to the page URL with an 'ask' query parameter. This is useful for retrieving information not explicitly present on the current page. ```http GET https://www.i18next.com/principles/plugins.md?ask= ``` -------------------------------- ### Perform HTTP GET Request to Query Documentation Source: https://www.i18next.com/translation-function/essentials Use this method to query the documentation dynamically. The question should be specific and in natural language. This is useful when the answer is not explicitly present, or you need clarification. ```http GET https://www.i18next.com/translation-function/essentials.md?ask= ``` -------------------------------- ### Reload Resources with i18next Source: https://www.i18next.com/overview/api Provides examples for reloading resources, with options to reload all resources, specific languages, specific namespaces, or a combination. It supports callbacks (for versions >= 11.9.0) and Promises. ```javascript // reload all i18next.reloadResources(); // reload languages i18next.reloadResources(['de', 'fr']); // reload namespaces for all languages i18next.reloadResources(null, ['ns1', 'ns2']); // reload namespaces in languages i18next.reloadResources(['de', 'fr'], ['ns1', 'ns2']); // reload a namespace in a language i18next.reloadResources('de', 'ns1'); // optional third param callback i18next@>=11.9.0 i18next.reloadResources('de', 'ns1', () => { /* reloaded */ }); // using Promises i18next .reloadResources() .then(() => {}); ``` -------------------------------- ### Browser Fallback with Bundled Resources Source: https://www.i18next.com/how-to/backend-fallback Configure i18next to use a primary http backend and fall back to local or bundled translations. This example uses `i18next-resources-to-backend` for in-memory bundled resources. ```javascript import i18next from "i18next"; import ChainedBackend from "i18next-chained-backend"; import HttpBackend from "i18next-http-backend"; import resourcesToBackend from "i18next-resources-to-backend"; const bundledResources = { en: { translation: { key: 'value' } } }; i18next .use(ChainedBackend) .init({ fallbackLng: "en", // ... your i18next config backend: { backends: [ HttpBackend, resourcesToBackend(bundledResources) ], backendOptions: [{ loadPath: '/locales/{{lng}}/{{ns}}.json' }] } }); ``` -------------------------------- ### Interpolation Example in English Source: https://www.i18next.com/principles/best-practices Demonstrates using interpolation for a dynamic value like payment type in an English string. This approach can lead to grammatical errors when translated. ```json { "key": "All fees will be charged to the {{paymentType}} on file for this account." } ``` -------------------------------- ### Browser Setup for i18next v2.0.0 Source: https://www.i18next.com/misc/migration-guide Integrate i18next with essential modules like XHR backend, local storage cache, language detection, and sprintf postprocessor for browser environments. ```javascript import i18next from 'i18next'; import XHR from 'i18next-xhr-backend'; import Cache from 'i18next-localstorage-cache'; import sprintf from 'i18next-sprintf-postprocessor'; import LanguageDetector from 'i18next-browser-languagedetector'; i18next .use(XHR) .use(Cache) .use(LanguageDetector) .use(sprintf) .init(options, callback); ``` -------------------------------- ### Instance Cloning Source: https://www.i18next.com/overview/api Creates a clone of the current i18next instance. This allows for independent configuration while sharing the store, plugins, and initial setup. The `forkResourceStore` option can be used to create a completely independent store. ```APIDOC ## 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. #### forkResourceStore By setting the forkResourceStore option to true, it will not shares the store. ### Request Example ```javascript const newInstance = i18next.cloneInstance({ fallbackLng: 'en', defaultNS: 'file1' }); const newInstance = i18next.cloneInstance({ forkResourceStore: true, keySeparator: '[[my-new-separator]]' }); ``` ``` -------------------------------- ### TypeScript: Fallback from Dialects/Scripts Source: https://www.i18next.com/principles/fallback Illustrates language variant fallback in TypeScript, similar to the JavaScript example, showing how to access translations from broader language versions when specific ones are missing. ```typescript i18next.init({ lng: "en-GB", resources: { "en-GB": { "translation": { "i18n": "Internationalisation" } }, "en": { "translation": { "i18n": "Internationalization", "i18n_short": "i18n" } } } }, () => { i18next.t($ => $.i18n); // -> finds "Internationalisation" i18next.t($ => $.i18n_short); // -> falls back to "en": "i18n" // force using en i18next.t($ => $.i18n, { lng: 'en' }); // -> "Internationalization" }); ``` -------------------------------- ### Initialize i18next with i18next-fs-backend Source: https://www.i18next.com/overview/first-setup-help Use this for serverless environments. Ensure the backend is imported and instantiated before initializing i18next. Do not include backend options within your main i18next options. ```javascript import i18next from 'i18next'; import Backend from 'i18next-fs-backend'; const backend = new Backend({ // path where resources get loaded from loadPath: '/locales/{{lng}}/{{ns}}.json' }); i18next .use(backend) .init({ // initAsync: false, // setting initAsync to false, will load the resources synchronously ...opts, ...yourOptions }); // yourOptions should not include backendOptions! ``` -------------------------------- ### i18next Initialization Options Source: https://www.i18next.com/overview/configuration-options Provides an overview of the options available when initializing i18next. ```APIDOC ## i18next Initialization ### Description Initializes the i18next internationalization framework with the provided options. ### Method `i18next.init(options, callback)` ### Endpoint N/A (This is a library function call) ### Parameters #### Options Object This object contains various configuration settings for i18next. - **debug** (boolean) - Optional - logs info level to console output. Helps finding issues with loading not working. ### Request Example ```javascript i18next.init({ debug: true }, function(err, t) { if (err) return console.log('something went wrong loading', err); console.log('i18next initialized'); }); ``` ### Response N/A (This is a function call, not an API endpoint with a direct response body.) ``` -------------------------------- ### Interpolation Example in German (Incorrect) Source: https://www.i18next.com/principles/best-practices Shows how interpolation can break grammar in German due to gendered articles. The example illustrates a common pitfall where 'dem' is used incorrectly with 'Kreditkarte'. ```json { "key": "Alle Beträge werden dem {{paymentType}} für dieses Konto in Rechnung gestellt." } ``` -------------------------------- ### Initialize and Manage Languages with i18next Source: https://www.i18next.com/overview/api Demonstrates initializing i18next with fallback languages, changing the current language, and observing the `i18next.languages` array which includes the new language and its more generic forms, followed by fallbacks. It also shows that previous languages are not retained when changing language again. ```javascript // initialize with fallback languages i18next.init({ fallbackLng: ["es", "fr", "en-US", "dev"] }); // change the language i18next.changeLanguage("en-US-xx"); // new language and its more generic forms, followed by fallbacks i18next.languages; // ["en-US-xx", "en-US", "en", "es", "fr", "dev"] // change the language again i18next.changeLanguage("de-DE"); // previous language is not retained i18next.languages; // ["de-DE", "de", "es", "fr", "en-US", "dev"] ``` -------------------------------- ### Initialize i18next with Namespaces (JavaScript) Source: https://www.i18next.com/principles/namespaces Initialize i18next with a list of namespaces and a default namespace. Use the `ns` option to specify all namespaces to be loaded and `defaultNS` to set the namespace for keys without a prefix. Load additional namespaces after initialization using `loadNamespaces`. ```javascript i18next.init({ ns: ['common', 'moduleA', 'moduleB'], defaultNS: 'moduleA' }, (err, t) => { i18next.t('myKey'); // key in moduleA namespace (defined default) i18next.t('common:myKey'); // key in common namespace (not recommended with ns prefix when used in combination with natural language keys) // better use the ns option: i18next.t('myKey', { ns: 'common' }); }); // load additional namespaces after initialization i18next.loadNamespaces('anotherNamespace', (err, t) => { /* ... */ }); ``` -------------------------------- ### Get Resource Data by Language Source: https://www.i18next.com/overview/api Retrieves all resource data associated with a specific language from i18next. ```javascript i18next.getDataByLanguage(lng) ``` -------------------------------- ### Initialize with Partial Bundled Languages and Backend Source: https://www.i18next.com/how-to/add-or-load-translations Configure i18next to allow for both pre-loaded (bundled) and lazily loaded translations via a backend. Set `partialBundledLanguages: true` and specify `ns` to control initial namespace loading. ```javascript import i18next from 'i18next'; i18next.init({ partialBundledLanguages: true, ns: [], resources: {} }); i18next.addResourceBundle('en', 'namespace1', { key: 'hello from namespace 1' }); // or via backend // i18next.loadNamespaces(['myNamespace1', 'myNamespace2']) // i18next.loadLanguages(['de', 'fr']) // etc. ``` -------------------------------- ### Integrate i18next Plugins Source: https://www.i18next.com/principles/plugins Demonstrates how to chain multiple i18next plugins, including a backend, language detector, and post-processor, during initialization. Ensure plugins are used in the desired order. ```javascript import i18next from 'i18next'; import Backend from 'i18next-http-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; import sprintf from 'i18next-sprintf-postprocessor'; i18next .use(Backend) // or any other backend implementation .use(LanguageDetector) // or any other implementation .use(sprintf) // or any other post processor .init(options); ``` -------------------------------- ### Initialize i18next with locize-backend Source: https://www.i18next.com/how-to/add-or-load-translations Use this snippet to configure i18next to load translations from locize via its CDN. Ensure you replace the placeholder values with your actual project credentials. ```javascript import i18next from 'i18next'; import Backend from 'i18next-locize-backend'; i18next .use(Backend) .init({ backend: { projectId: '[PROJECT_ID]', apiKey: '[API_KEY]', referenceLng: '[LNG]' } }); ``` -------------------------------- ### Language Code Example Source: https://www.i18next.com/principles/translation-resolution Demonstrates the format of language codes used in i18next, including pure language codes and those with regional variants. ```plaintext "en-US" ``` -------------------------------- ### Using `useTranslation` with a namespace Source: https://www.i18next.com/overview/typescript This example shows how to use the `useTranslation` hook with a specific namespace, which might be relevant when dealing with type inference issues. ```typescript const { t } = useTranslation(`${ns}Default`); ``` -------------------------------- ### Lazy Load Translations with resources-to-backend Source: https://www.i18next.com/how-to/add-or-load-translations Utilize the `i18next-resources-to-backend` plugin to transform resources into a backend, enabling lazy loading of translations, for example, with webpack. ```javascript import i18next from 'i18next'; import resourcesToBackend from 'i18next-resources-to-backend'; i18next .use(resourcesToBackend((language, namespace) => import(`./locales/${language}/${namespace}.json`))) .init({ /* other options */ }) ``` -------------------------------- ### Server-Side Caching with Filesystem Source: https://www.i18next.com/how-to/caching Set up i18next for server-side caching using FsBackend, with HttpBackend as a fallback. Ensure the cache directory exists. ```javascript import i18next from "i18next"; import ChainedBackend from "i18next-chained-backend"; import HttpBackend from "i18next-http-backend"; import FsBackend from "i18next-fs-backend"; i18next .use(ChainedBackend) .init({ fallbackLng: "en", // ... your i18next config backend: { backends: [ FsBackend, HttpBackend ], backendOptions: [{ expirationTime: 7 * 24 * 60 * 60 * 1000, // 7 days loadPath: './locales_cache/{{lng}}/{{ns}}.json', addPath: './locales_cache/{{lng}}/{{ns}}.json' // make sure the folders "locales_cache/{{lng}}" exists }, { loadPath: '/locales/{{lng}}/{{ns}}.json' }] } }); ``` -------------------------------- ### Determine Text Direction with i18next Source: https://www.i18next.com/overview/api Shows how to get the text direction ('rtl' or 'ltr') for the current language or a specified language code using `i18next.dir()`. ```javascript // for current language i18next.dir(); // for another language i18next.dir('en-US'); // -> "ltr"; i18next.dir('ar'); // -> "rtl"; ``` -------------------------------- ### Configure Namespaces and Fallbacks in i18next (JavaScript) Source: https://www.i18next.com/principles/fallback Initialize i18next with multiple namespaces and a fallback namespace. This allows keys to be looked up in 'common' if not found in 'app'. ```javascript i18next.init({ // files to load ns: ['app', 'common'], // default namespace (needs no prefix on calling t) defaultNS: 'app', // fallback, can be a string or an array of namespaces fallbackNS: 'common' }, () => { i18next.t('title') // -> "i18next" i18next.t('button.save') // -> "save" (fallback from common) // without fallbackNS you would have to prefix namespace // to access keys in that namespace // and this is not recommended when used in combination with natural language keys i18next.t('common:button.save') // -> "save" // better use the ns option: i18next.t('button.save', { ns: 'common' }) // -> "save" }); ``` -------------------------------- ### Basic Nesting Usage Source: https://www.i18next.com/translation-function/nesting Call the t function with a nested key to resolve the full translation string. The example demonstrates how nested keys are evaluated sequentially. ```javascript i18next.t('nesting1'); // -> "1 2 3" ``` ```typescript i18next.t($ => $.nesting1); // -> "1 2 3" ``` -------------------------------- ### Initialize i18next with Async/Await (JavaScript) Source: https://www.i18next.com/overview/getting-started Initializes i18next using async/await syntax for modern asynchronous JavaScript. ```javascript await i18next.init({ lng: 'en', // if you're using a language detector, do not define the lng option debug: true, resources: { en: { translation: { "key": "hello world" } } } }); // initialized and ready to go! document.getElementById('output').innerHTML = i18next.t('key'); ``` -------------------------------- ### Example of Skipping Variable Interpolation Source: https://www.i18next.com/translation-function/interpolation Illustrates `skipOnVariables` behavior with differently formatted variables. When `true`, `{{otherVar}}` is not resolved. If `false`, it would attempt to resolve `otherVar`. ```javascript t('key', { a: '{{otherVar}}': otherVar: 'another value' }) ``` -------------------------------- ### Initialize i18next with bundled resources Source: https://www.i18next.com/overview/first-setup-help Import translation files directly and provide them in the resources option during initialization. This is suitable for bundling translations with your application. ```javascript import i18next from 'i18next'; import en from './locales/en.json' import de from './locales/de.json' i18next .init({ ...opts, ...yourOptions, resources: { en, de } }); ``` -------------------------------- ### Initialize i18next with Promises (JavaScript) Source: https://www.i18next.com/overview/getting-started Initializes i18next using Promises, allowing for cleaner asynchronous handling with .then(). ```javascript i18next.init({ lng: 'en', // if you're using a language detector, do not define the lng option debug: true, resources: { en: { translation: { "key": "hello world" } } } }).then(function(t) { // initialized and ready to go! document.getElementById('output').innerHTML = i18next.t('key'); }); ``` -------------------------------- ### Get Fixed Translation Function with Key Prefix (TypeScript) Source: https://www.i18next.com/overview/api In TypeScript, getFixedT can be used with a key prefix. Note that the t function signature differs, accepting a selector function for keys. ```typescript const t = i18next.getFixedT(null, null, 'user.accountSettings.changePassword') const title = t($ => $.title); // same as i18next.t($ => $.user.accountSettings.changePassword.title); ``` -------------------------------- ### Initializing i18next with Namespaces Source: https://www.i18next.com/translation-function/essentials Configure i18next to load translations from multiple namespaces by specifying them in the `ns` array and setting a `defaultNS`. ```javascript i18next.init({ ns: ['common', 'moduleA'], defaultNS: 'moduleA' }); ``` -------------------------------- ### Get Fixed Translation Function with Key Prefix (JavaScript) Source: https://www.i18next.com/overview/api Use getFixedT to create a t function with a default namespace prefix. This simplifies translation calls by automatically applying the prefix. ```javascript const t = i18next.getFixedT(null, null, 'user.accountSettings.changePassword') const title = t('title'); // same as i18next.t('user.accountSettings.changePassword.title'); ``` -------------------------------- ### Run v2.0.0 with v1.11.x Compatibility Flags Source: https://www.i18next.com/misc/migration-guide Initialize i18next v2.0.0 using compatibility flags for API and JSON format to mimic v1.11.x behavior. This layer will be removed in future versions. ```javascript import i18next from 'i18next'; i18next.init({ compatibilityAPI: 'v1', compatibilityJSON: 'v1', // ...old options from v1 }, (err, t) => { /* resources are loaded */ }); ``` -------------------------------- ### Example of Skipping Interpolation Source: https://www.i18next.com/translation-function/interpolation Demonstrates how `skipOnVariables` prevents nested key resolution. When `true`, `$t(nested)` is treated as a literal string. If `false`, it would attempt to resolve the nested key. ```javascript t('key', { a: '$t(nested)' }) ``` -------------------------------- ### TypeScript Interval Plural Usage Source: https://www.i18next.com/translation-function/plurals Illustrates using `postProcess: 'interval'` with `i18next.t` in TypeScript for interval-based plural selection. Includes examples of range matching and fallback to regular plurals. ```typescript i18next.t($ => $.key1_interval, {postProcess: 'interval', count: 1}); // -> "one item" i18next.t($ => $.key1_interval, {postProcess: 'interval', count: 4}); // -> "a few items" i18next.t($ => $.key1_interval, {postProcess: 'interval', count: 100}); // -> "a lot of items" // not matching into a range it will fallback to // the regular plural form i18next.t($ => $.key2_interval, {postProcess: 'interval', count: 1}); // -> "one item" i18next.t($ => $.key2_interval, {postProcess: 'interval', count: 4}); // -> "a few items" i18next.t($ => $.key2_interval, {postProcess: 'interval', count: 100}); // -> "100 items" ``` -------------------------------- ### Initialize i18next with Options and Callback Source: https://www.i18next.com/overview/api Initialize the i18next instance with configuration options and a callback function. The callback is executed after translations are loaded or if an error occurs. Ensure you wait for initialization to complete before using the 't' function. ```javascript 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'); }); ``` ```typescript 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); }); ``` -------------------------------- ### Pages Router Client-side Caching with Locize Source: https://www.i18next.com/how-to/caching Configure your `next-i18next.config.js` for Pages Router to enable client-side caching with Locize. This setup uses `LocalStorageBackend` and `LocizeBackend` conditionally for browser environments. ```javascript // next-i18next.config.js const LocizeBackend = require('i18next-locize-backend/cjs') const ChainedBackend = require('i18next-chained-backend').default const LocalStorageBackend = require('i18next-localstorage-backend').default const isBrowser = typeof window !== 'undefined' module.exports = { i18n: { defaultLocale: 'en', locales: ['en', 'de'], }, backend: { backendOptions: [{ expirationTime: 60 * 60 * 1000 // 1 hour }, { projectId: '[PROJECT_ID]', version: 'latest' }], backends: isBrowser ? [LocalStorageBackend, LocizeBackend] : [], }, partialBundledLanguages: isBrowser && true, serializeConfig: false, use: isBrowser ? [ChainedBackend] : [], } ``` -------------------------------- ### Initialization API Source: https://www.i18next.com/overview/api The `init` function is used to initialize the i18next instance with configuration options and a callback function or a Promise. It's crucial to wait for initialization to complete before using translation functions. ```APIDOC ## init `i18next.init(options, callback)` Initializes the i18next instance. The callback is invoked after translations are loaded or an error occurs. Promises are also supported for asynchronous initialization. ### Parameters #### Options (`options`) Refer to the [options page](https://www.i18next.com/overview/configuration-options) for a comprehensive list of configuration options. #### Callback (`callback`) A function that accepts two arguments: `err` (error object if initialization failed) and `t` (the translation function). ### Request Example ```javascript 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'); }); // Using Promises i18next .init({ /* options */ }) .then(function(t) { t('key'); }); ``` ### Response Upon successful initialization, the callback receives a translation function `t`. ``` -------------------------------- ### Configure Namespaces and Fallbacks in i18next (TypeScript) Source: https://www.i18next.com/principles/fallback Initialize i18next with multiple namespaces and a fallback namespace using TypeScript syntax. Keys not found in the default namespace will fall back to 'common'. ```typescript i18next.init({ // files to load ns: ['app', 'common'], // default namespace (needs no prefix on calling t) defaultNS: 'app', // fallback, can be a string or an array of namespaces fallbackNS: 'common' }, () => { i18next.t($ => $.title) // -> "i18next" i18next.t($ => $.button.save) // -> "save" (fallback from common) // switch namespaces with the `ns` option: i18next.t($ => $.button.save, { ns: 'common' }) // -> "save" }); ``` -------------------------------- ### Interval Plural Keys Example Source: https://www.i18next.com/translation-function/plurals Defines translation keys for interval plurals. The `_interval` key specifies ranges and corresponding translations, falling back to regular plurals if no range matches. ```javascript { "key1_one": "{{count}} item", "key1_other": "{{count}} items", "key1_interval": "(1)[one item];(2-7)[a few items];(7-inf)[a lot of items];", "key2_one": "{{count}} item", "key2_other": "{{count}} items", "key2_interval": "(1)[one item];(2-7)[a few items];" } ``` -------------------------------- ### Initialize i18next with Promises (TypeScript) Source: https://www.i18next.com/overview/getting-started Initializes i18next using Promises in TypeScript. The .then() block executes after successful initialization. ```typescript i18next.init({ lng: 'en', // if you're using a language detector, do not define the lng option debug: true, resources: { en: { translation: { "key": "hello world" } } } }).then(function(t) { // initialized and ready to go! document.getElementById('output').innerHTML = i18next.t($ => $.key); }); ``` -------------------------------- ### Declare i18next Types with Exported Resources Source: https://www.i18next.com/overview/typescript Define the i18next module augmentation using exported resources and defaultNS from your configuration file. This ensures consistency between your i18next setup and type definitions. ```typescript import { resources, defaultNS } from "./i18n"; declare module "i18next" { interface CustomTypeOptions { defaultNS: typeof defaultNS; resources: typeof resources["en"]; } } ``` -------------------------------- ### Initialize i18next with Namespaces (TypeScript) Source: https://www.i18next.com/principles/namespaces Initialize i18next with a list of namespaces and a default namespace in TypeScript. Use the `ns` option to specify all namespaces to be loaded and `defaultNS` to set the namespace for keys without a prefix. Load additional namespaces after initialization using `loadNamespaces`. ```typescript i18next.init({ ns: ['common', 'moduleA', 'moduleB'], defaultNS: 'moduleA' }, (err, t) => { i18next.t($ => $.myKey); // key in moduleA namespace (defined default) i18next.t($ => $.myKey, { ns: 'common' }); // key in common namespace }); // load additional namespaces after initialization i18next.loadNamespaces('anotherNamespace', (err, t) => { /* ... */ }); ``` -------------------------------- ### Create New i18next Instance with Options Source: https://www.i18next.com/overview/api Creates a new, independent i18next instance with specified configuration options and an optional callback for initialization. The callback is invoked after translations are loaded or upon an error. ```javascript const newInstance = i18next.createInstance({ 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 }); // is the same as const newInstance = i18next.createInstance(); newInstance.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 }); ``` -------------------------------- ### Ordinal Plural Keys Example Source: https://www.i18next.com/translation-function/plurals Defines translation keys for ordinal plurals in English. Use these when the count's ordinal digit determines the plural form (e.g., 1st, 2nd, 3rd). ```javascript // i.e. english { "key_ordinal_one": "{{count}}st place", // 1st, 21st, 31st "key_ordinal_two": "{{count}}nd place", // 2nd, 22nd, 32nd "key_ordinal_few": "{{count}}rd place", // 3rd, 23rd, 33rd "key_ordinal_other": "{{count}}th place" // 4th, 5th, 24th, 11th } ``` -------------------------------- ### Instance Creation Source: https://www.i18next.com/overview/api Creates a new i18next instance. An optional callback can be provided to automatically initialize the instance and handle translation loading. ```APIDOC ## createInstance `i18next.createInstance(options, callback)` Will return a new i18next instance. Providing a callback will automatically call init. The callback will be called after all translations were loaded or with an error when failed (in case of using a backend). ### Request Example ```javascript const newInstance = i18next.createInstance({ 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 }); // is the same as const newInstance = i18next.createInstance(); newInstance.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 }); ``` ``` -------------------------------- ### Risky Pattern: Interpolated Values in Nesting Options Source: https://www.i18next.com/translation-function/nesting This example demonstrates a potentially insecure pattern where user-controlled input is interpolated within a nesting-options block. This can lead to security vulnerabilities if `escapeValue` is set to `false`. ```javascript { "title": "$t(greeting, { \"count\": \"{{userCount}}\" })", "greeting_one": "One item", "greeting_other": "{{count}} items" } ```