Installation
To use Tolgee with i18next, you need to follow these steps:
- Install the Tolgee integration library
- Set up the environment variables
- Initialize Tolgee
- Language Detection and Switching
- Preparing for production
Installation
To install the Tolgee i18next integration library, run the following command.
- npm
- yarn
- pnpm
npm install @tolgee/i18next
yarn add @tolgee/i18next
pnpm install @tolgee/i18next
Set up the environment variables
Once the library is installed, you need to initialize it. For initialization, you need the Tolgee API URL, and the Tolgee API Key. To generate the API Key, follow the step-by-step instructions mentioned on the API keys and PAT tokens page.
Make sure you don't leak your API key. If the API key is leaked, visitors can edit the translations on your site.
After generating the API key, add these credentials in an environment variable file (.env
or .env.local
).
Initialize Tolgee
Next, initialize Tolgee and wrap your i18next instance using withTolgee
.
import i18n from 'i18next';
import { withTolgee, Tolgee, I18nextPlugin, DevTools } from '@tolgee/i18next';
const tolgee = Tolgee()
.use(DevTools())
.use(I18nextPlugin())
.init({
// for development
apiUrl: ...,
apiKey: ...,
// for production
staticData: {
'en:translation': ...,
'cs:translation': ...
}
});
withTolgee(i18n, tolgee)
.use(...)
.init(...)
The above code does the following:
- Initializes Tolgee with the provided configuration.
- Wraps the i18next instance with the
withTolgee
function. - Initializes i18next with the provided configuration.
You can configure more options and plugins during initialization. Learn about these other options and Tolgee plugins in their respective documentation.
Tolgee maps i18next
namespaces to its own namespaces. Since i18next doesn't support empty namespaces, ensure your translations are within a namespace in the Tolgee platform. By default, i18next uses the "translation" namespace.
Language Detection and Switching
Tolgee follows i18next's configuration for language detection. You can use i18next language detectors or set the language manually.
To change the active language, use the i18next.changeLanguage
function:
i18next.changeLanguage(lng, callback);
Preparing for production
Tolgee will automatically omit DevTools
from your bundle when you build your app for production. So it won't fetch translations directly from Tolgee Platform and it won't allow users to modify translations.
There are generally two ways how to use translations in production:
- Tolgee Content Delivery - translations are loaded dynamically from fast and reliable storage
- Providing localization files directly - your translations are bundled with your code
In production mode, you should never use localization data directly from Tolgee REST API, because it can negatively affect your page performance.