Skip to main content
Version: 5.x.x

Using with Gatsby

To use Tolgee with Gatsby follow this Guide.

Prerequisites

  1. Created Gatsby project with installed @tolgee/react module
  2. Created project in Tolgee platform with 2 languages. In our case it is English (en) and Czech (cs).
  3. Added some localization key and translations for both languages. In our case the key name is hello_world
  4. Generated API key for your project
  5. Exported data as zip of jsons

Set up your environment.

Create file (if not exists) .env.development and add this content to it.

GATSBY_TOLGEE_API_KEY=<your api key>
GATSBY_TOLGEE_API_URL=https://app.tolgee.io

Then replace <your api key> with your generated API key.

Save exported data to project structure

Save exported json files to src/i18n folder in your project structure.

Use Intl extension

npm install gatsby-plugin-react-intl
gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-react-intl`,
options: {
path: `${__dirname}/src/i18n`,
languages: [`en`, `cs`],
defaultLanguage: `en`,
redirect: true,
},
},
],
};

Use TolgeeProvider

info

useTolgeeSSR function was added in SDK version 5.5

import { useIntl } from 'gatsby-plugin-react-intl';

const tolgee = Tolgee()
.use(DevTools())
.init({
defaultLanguage: 'en',
apiKey: process.env.GATSBY_TOLGEE_API_KEY,
apiUrl: process.env.GATSBY_TOLGEE_API_URL,
staticData: {
en: () => import(`../i18n/en.json`),
de: () => import('../i18n/de.json'),
},
})

export const AppWrapper: React.FC = ({ children }) => {
const { locale, messages } = useIntl();

const staticData = useMemo(() => {
return { [locale]: messages }
}, [locale, messages])

// sync tolgee with locale and adds locales into cache
// makes sure first render matches the server one
const ssrTolgee = useTolgeeSSR(tolgee, locale, staticData);

return (
<TolgeeProvider
tolgee={ssrTolgee}
fallback={<div>Loading...</div>}
>
{children}
</TolgeeProvider>
);
};

Intl plugin manages locale for us and also gives us content of localization file based on locale, which we provide statically to Tolgee. On production Gatsby will generate pages separately for each locale, so only locale that is needed is provided statically.

Change language with intl plugin

import { useTolgee } from '@tolgee/react';
import { changeLocale } from 'gatsby-plugin-react-intl';

export const LangSelector: React.FC = () => {
const tolgee = useTolgee(['language']);

return (
<select
onChange={(e) => changeLocale(e.target.value)}
value={tolgee.getLanguage()}
>
<option value="en">🇬🇧 English</option>
<option value="cs">🇨🇿 Česky</option>
</select>
);
};

You are done! Now you can translate your strings directly in your application, and enjoy the features of Gatsby in the same time! You can find final application code in this repo: github.com/tolgee/gatsby-example.

Now you can use translation methods described here.