Next.js with Pages Router
You can also check the Next pages router example application to learn more.
Prerequisites
- An existing Next.js project. Install the
@tolgee/react
package. - An existing project on Tolgee platform with at least 2 languages. This guide uses English (en) and Czech (cs).
- Add localization keys and translations for both the languages. This guide uses the key name
hello_world
. - API key of your Tolgee project.
- Exported localization data in JSON format.
Prepare your next-config
Add the i18n
config into your next-config.js
file as follow.
/** @type {import('next').NextConfig} */
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.
NEXT_PUBLIC_TOLGEE_API_KEY=<your api key>
NEXT_PUBLIC_TOLGEE_API_URL=https://app.tolgee.io
Save exported data
Create an i18n
folder in the root of your project directory, if it does not already exists. Move the exported localization json files to the i18n
folder.
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.
useTolgeeSSR
function was added in the 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, FormatSimple } 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;
To optimize the bundle size include only the locale needed for the 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 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.
To learn more about checkout this example: github.com/tolgee/next-example.