Fetching translations
New in SDK version 6
Tolgee SDK can be used to load correct translation files simply from the Tolgee platform or static data. This is primarily useful on the server when you need to prefetch data and pass them to frontend as a JSON.
These methods also load the data to the cache, so you can then call t
function to render the translations.
loadRequired
This method fetches the same data as tolgee.run()
method - based on current options of language
, ns
(and their fallbacks).
// on the server
const translations = JSON.stringify(await tolgee.loadRequired())
// ... pass translations to the client
// on the client
tolgee.addStaticData(translations)
// now the client doesn't have to fetch anything, when `run` is called
Check the method API
loadMatrix
Use this method for easy prefetching of user-defined records.
const translations = await tolgee.loadMatrix({
languages: ['en', 'cs']
namespaces: ['common', 'info']
})
// loads `en:common`, `en:info`, `cs:common` and `cs:info` records
Let's say we want to load all namespaces on the server so we can render them without loading them later.
await tolgee.loadMatrix({
languages: ['en']
namespaces: 'all'
})
// now all namespaces are now prefetched for English
t('app_title', { ns: 'info' })
For this to work, you need to specify availableNs
or availableLanguages
.
Check the method API
Data caching on the server
By default these methods always re-fetch the data when called (requests are only de-duped).
If you want to re-use already fetched data from the cache, you can pass option { useCache: true }
.
However, on the server, this is not recommended, because until the tolgee instance is live, the data wouldn't be renewed.
Instead, we recommend an external caching solution (for example next.js caching).