Skip to main content
Version: 5.x.x

SSR support

To use Tolgee with your SSR framework such as Next.js, you can provide localization data imported as object using staticData property of TolgeeProvider component, this data will be loaded directly into cache and immediately available with first render for SSR. We also need to know user's locale already on the server and set it through Tolgee language option.

info

useTolgeeSSR function was added in SDK version 5.5

import localeEn from 'i18n/en.json';
import localeDe from 'i18n/de.json';

...

const tolgee = Tolgee()
.use(DevTools())
.use(FormatSimple())
.init({
defaultLanguage: 'en',
staticData: {
en: localeEn,
de: localeDe,
}
})

const App = () => {
// this needs to work on server
const language = ?

// sync tolgee language with locale recieved on server
const ssrTolgee = useTolgeeSSR(tolgee, locale);

return (
<TolgeeProvider
tolgee={ssrTolgee}
...
>
...
</TolgeeProvider>
)
}

We use useTolgeeSSR to safely sync locale as that need to be ready for the first render on the server.

With this approach we include all translations directly in the bundle regardless user locale. For smaller projects this is not a big issue, however it might be significant for large applications with many translations and languages.

For these cases we need to only provide statically the locale, that the user is currently using. We can also use async functions in staticData which will be used for fetching translations dynamically on client side (you can use this instead of having them in public folder).


const tolgee = Tolgee()
.use(DevTools())
.use(FormatSimple())
.init({
defaultLanguage: 'en',
})

const App = () => {
// we need to get these on server, which we'll need to implement
// differently for each framework
const language = ?
const staticData = ?

// sync language and add static data to be ready in cache
const ssrTolgee = useTolgeeSSR(tolgee, language, staticData);

return (
<TolgeeProvider
tolgee={ssrTolgee}
...
>
...
</TolgeePrivider>
)
}

Language changing

When we use SSR, we have to specify language in a way that is detectable by both client and server. Easiest way is to include it directly in URL - next.js has support for this.

Then for language change we use the native way of the framework.