Skip to main content

Using with Next.js

To use localize your Next.js app you can use the Next.js i18n-routing feature.

Prerequisites#

  1. Created Next.js project with installed @tolgee/react and @tolgee/ui modules
  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'],        localeDetection: true,        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.

import '../styles/globals.css'import type {AppProps} from 'next/app'import UI from "@tolgee/ui";import enLocale from "../i18n/en.json";import csLocale from "../i18n/cs.json";import {useRouter} from "next/router";import {TolgeeProvider} from "@tolgee/react";
function MyApp({Component, pageProps}: AppProps) {const {locale: activeLocale} = useRouter()
    return <TolgeeProvider        ui={UI}        forceLanguage={activeLocale}        apiKey={process.env.NEXT_PUBLIC_TOLGEE_API_KEY}        apiUrl={process.env.NEXT_PUBLIC_TOLGEE_API_URL}        staticData={{            en: enLocale,            cs: csLocale        }}    >        <Component {...pageProps} />    </TolgeeProvider>}
export default MyApp

The forceLanguage prop forces Tolgee to use the language which is provided by Next.js. It will not try to change it using its own way.

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 the example application code in this repo: github.com/tolgee/next-example.

Now you can use translation methods described here.