Skip to main content
Version: 5.x.x

Next.js with pages router

Check our Next pages router example application

Prerequisites

  1. Created Next.js 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 (stored somewhere)

Prepare your next-config

First you have to add i18n settings into your next-config.js.

/** @type {import('next').NextConfig} */
module.exports = {
reactStrictMode: true,
i18n: {
locales: ['en', 'cs'],
defaultLocale: 'en',
},
};

Set up your environment.

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

NEXT_PUBLIC_TOLGEE_API_KEY=<your api key>
NEXT_PUBLIC_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 i18n folder in your project structure.

Add TolgeeProvider

Then wrap your main component with TolgeeProvider component. Import the localization data and provide them to TolgeeProvider using staticData prop.

info

useTolgeeSSR function was added in SDK version 5.5

import { useState } from 'react';
import type { AppProps } from 'next/app';
import enLocale from '../i18n/en.json';
import csLocale from '../i18n/cs.json';
import { useRouter } from 'next/router';
import { TolgeeProvider, DevTools, Tolgee, useTolgeeSSR } from '@tolgee/react';

const tolgee = Tolgee().use(DevTools()).use(FormatSimple()).init({
staticData: {
en: enLocale,
cs: csLocale,
},
defaultLanguage: 'en',
apiKey: process.env.NEXT_PUBLIC_TOLGEE_API_KEY,
apiUrl: process.env.NEXT_PUBLIC_TOLGEE_API_URL,
});

function MyApp({ Component, pageProps }: AppProps) {
const router = useRouter();

// sync tolgee with router.locale
// make sure first render matches the server one
const ssrTolgee = useTolgeeSSR(tolgee, router.locale);

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

export default MyApp;

We can optimize bundle size by only including locale which is needed for rendered page by using getInitialProps.

const tolgee = Tolgee().use(DevTools()).use(FormatSimple()).init({
defaultLanguage: 'en',
apiKey: process.env.NEXT_PUBLIC_TOLGEE_API_KEY,
apiUrl: process.env.NEXT_PUBLIC_TOLGEE_API_URL,
});

function MyApp({ Component, pageProps, staticData }: AppProps) {
const { locale: activeLocale } = useRouter();

// adding locales static data recieved from getInitialProps
const ssrTolgee = useTolgeeSSR(tolgee, router.locale, staticData);

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

MyApp.getInitialProps = async (context) => {
const locale = context.router.locale;
const result = {
staticData: {
[locale]: await import(`../i18n/${locale}.json`),
},
};
return result;
};

Similarly, you can use getServerSideProps or getStaticProps on each page.

Change language with next.js router

As we need locale information both on server and client we need to use next.js native way.

import { useRouter } from 'next/router';

export const LangSelector: React.FC = () => {
const router = useRouter();
const setLanguage = (lang: string) => {
router.replace(router.pathname, undefined, { locale: lang });
};

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

Use T component to translate something

Use T component to translate some text somewhere in your app.

<h1>
<T>hello_world</T>
</h1>

You are done! Now you can translate your strings directly in your application, and enjoy the features of Next.js in the same time! You can find even more complex example application code in this repo: github.com/tolgee/next-example.

Now you can use translation methods described here.

To get more information read React docs, Tolgee general docs or check the Example app.