Skip to main content
Version: 5.x.x

Next.js with Pages Router

tip
You can also check the Next pages router example application to learn more.

Prerequisites

  1. An existing Next.js project. Install the @tolgee/react package.
  2. An existing project on Tolgee platform with at least 2 languages. This guide uses English (en) and Czech (cs).
  3. Add localization keys and translations for both the languages. This guide uses the key name hello_world.
  4. API key of your Tolgee project.
  5. Exported localization data in JSON format.

Install the required packages

To implement localization to your app, you need to install the @tolgee/react package:

npm install @tolgee/react
info

Use @tolgee/react version 5.30.0 and higher

Folder structure

The folder structure of your project should resemble the following:

├── .env.development.local    # ignored by git
├── next.config.js
├── messages
│ ├── en.json
│ └── cs.json
└── src
├── tolgee.ts
└── pages
└── _app.tsx

Prepare your next-config

Add the i18n config into your next-config.js file as follow.

next.config.js
module.exports = {
reactStrictMode: true,
i18n: {
locales: ['en', 'cs'],
defaultLocale: 'en',
},
};

Set up your environment

Create the .env.development.local file if it does not exist. You will store the Tolgee credentials securely in this file.

Paste the following in the newly created file. Replace <your api key> with your Tolgee API key.

.env.development.local
NEXT_PUBLIC_TOLGEE_API_KEY=<your api key>
NEXT_PUBLIC_TOLGEE_API_URL=https://app.tolgee.io

Save exported data

Create an messages folder in the root of your project directory, if it does not already exists. Move the exported localization json files to the messages folder.

Create Tolgee setup file

This file contains tolgee setup and helper function for loading static files.

src/tolgee.ts
import { FormatIcu } from '@tolgee/format-icu';
import { Tolgee, DevTools } from '@tolgee/react';

export async function getStaticData(
languages: string[],
namespaces: string[] = ['']
) {
const result: Record<string, any> = {};
for (const lang of languages) {
for (const namespace of namespaces) {
if (namespace) {
result[`${lang}:${namespace}`] = (
await import(`../messages/${namespace}/${lang}.json`)
).default;
} else {
result[lang] = (await import(`../messages/${lang}.json`)).default;
}
}
}
return result;
}

export const tolgee = Tolgee()
.use(FormatIcu())
.use(DevTools())
.init({
availableLanguages: ['en', 'cs'],
defaultLanguage: 'en',
apiKey: process.env.NEXT_PUBLIC_TOLGEE_API_KEY,
apiUrl: process.env.NEXT_PUBLIC_TOLGEE_API_URL,
});

Add the TolgeeProvider

The next step is to wrap the application's main component with the TolgeeProvider component.

Import the localization data and provide them to the TolgeeProvider using the staticData prop.

src/pages/_app.tsx
import type { AppContext, AppInitialProps, AppProps } from 'next/app';
import { getStaticData, tolgee } from '../tolgee';
import App from 'next/app';
import { TolgeeProvider, TolgeeStaticData } from '@tolgee/react';
import { useRouter } from 'next/router';

type AppOwnProps = { staticData: TolgeeStaticData };

export default function MyApp({
Component,
pageProps,
staticData,
}: AppProps & AppOwnProps) {
const router = useRouter();
return (
<TolgeeProvider
tolgee={tolgee}
ssr={{ language: router.locale, staticData }}
>
<Component {...pageProps} />
</TolgeeProvider>
);
}


MyApp.getInitialProps = async (
context: AppContext
): Promise<AppOwnProps & AppInitialProps> => {
const ctx = await App.getInitialProps(context);
return { ...ctx, staticData: await getStaticData([context.ctx.locale!]) };
};

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

Change language with the Next.js router

The application needs locale information both on server and client. The application can get this infromation native way as follows.

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 for translation

The next step is to render the translated text for the selected locale. Use the T component to translate the text in your app.

<h1>
<T key_name="hello_world" />
</h1>

That's it! You have successfully implemented translation to your Next.js applicaiton. You can also use translation methods described in the React Translating documentation.

tip
You can also check the Next pages router example application to learn more.