Next.js with App Router & router-based localizaton
This guide shows how to include language information into the page URL, so your application is SEO friendly.
Installation
The Next.js App Router does not provide native support for i18n
routing as the Page Router does. However, you can use the next-intl
library, for routing and locale detection.
We are not using an entire functionality of the library, so the setup is missing some pieces from official documentation of next-intl.
Follow the below instructions to learn to implement localization to your Next.js App Router app with Tolgee.
Prerequisites
- An existing Next.js project.
- 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.
Install the required packages
To implement localization to your app, you need to install the next-intl
and @tolgee/react
package. Execute the following command to install the package.
npm install next-intl @tolgee/react
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
├── middleware.ts
├── navigation.ts
├── i18n
│ └── request.ts
├── tolgee
│ ├── shared.ts
│ ├── client.tsx
│ └── server.tsx
└── app
└── [locale]
├── layout.tsx
└── page.tsx
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 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.
Set up Tolgee
You need to set up Tolgee for both the client and the server. You can create shared configuration that can be used for both client and server.
Shared configuration
In your tolgee/shared.ts
file, add the following code.
import { DevTools, Tolgee, FormatSimple } from '@tolgee/web';
const apiKey = process.env.NEXT_PUBLIC_TOLGEE_API_KEY;
const apiUrl = process.env.NEXT_PUBLIC_TOLGEE_API_URL;
export const ALL_LANGUAGES = ['en', 'cs', 'de', 'fr'];
export const DEFAULT_LANGUAGE = 'en';
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 function TolgeeBase() {
return Tolgee()
.use(FormatSimple())
.use(DevTools())
// replace with .use(FormatIcu()) for rendering plurals, foramatted numbers, etc.
.updateDefaults({
apiKey,
apiUrl,
});
}
Client configutation
The client configuration is very similar to the Pages Router set up. It serves the purpose of translating client components and also enables the in-context functionality for server-rendered components.
'use client';
import { useEffect } from 'react';
import { TolgeeProvider, TolgeeStaticData } from '@tolgee/react';
import { useRouter } from 'next/navigation';
import { TolgeeBase } from './shared';
type Props = {
staticData: TolgeeStaticData;
language: string;
children: React.ReactNode;
};
const tolgee = TolgeeBase().init();
export const TolgeeNextProvider = ({
language,
staticData,
children,
}: Props) => {
const router = useRouter();
useEffect(() => {
const { unsubscribe } = tolgee.on('permanentChange', () => {
router.refresh();
});
return () => unsubscribe();
}, [tolgee, router]);
return (
<TolgeeProvider
tolgee={tolgee}
options={{ useSuspense: false }}
fallback="Loading"
ssr={{ language, staticData }}
>
{children}
</TolgeeProvider>
);
};
Server configuration
Your app will utilize the React server cache for sharing Tolgee instance across components in a single render. This allows the app to use the Tolgee instance anywhere in the server components.
One important difference from the client setup is the utilization of fullKeyEncode
. fullKeyEncode
ensures that translations rendered on the server are correctly picked up and interactive for in-context mode.
import { getLocale } from 'next-intl/server';
import { TolgeeBase, ALL_LANGUAGES, getStaticData } from './shared';
import { createServerInstance } from '@tolgee/react/server';
export const { getTolgee, getTranslate, T } = createServerInstance({
getLocale: getLocale,
createTolgee: async (language) =>
TolgeeBase().init({
// including all languages
// on server we are not concerned about bundle size
staticData: await getStaticData(ALL_LANGUAGES),
observerOptions: {
fullKeyEncode: true,
},
language,
// using custom fetch to avoid aggressive caching
fetch: async (input, init) =>
fetch(input, { ...init, next: { revalidate: 0 } }),
}),
});
Use the TolgeeNextProvider
The next step is to wrap the children with the TolgeeNextProvider
. Update the layout.tsx
file with the following code:
import { notFound } from 'next/navigation';
import { ReactNode } from 'react';
import { TolgeeNextProvider } from '@/tolgee/client';
import { ALL_LANGUAGES, getStaticData } from '@/tolgee/shared';
type Props = {
children: ReactNode;
params: { locale: string };
};
export default async function LocaleLayout({
children,
params: { locale },
}: Props) {
if (!ALL_LANGUAGES.includes(locale)) {
notFound();
}
// it's important you provide all data which are needed for initial render
// so current language and also fallback languages + necessary namespaces
const staticData = await getStaticData([locale, 'en']);
return (
<html lang={locale}>
<body>
<TolgeeNextProvider language={locale} staticData={staticData}>
{children}
</TolgeeNextProvider>
</body>
</html>
);
}
The above code loads relevant locale available on the server and pass it to the client component through props.
This example provides translation globally. If you want to provide each page with a different namespace, you can move the provider to the relevant page files.
Set up next-intl
To use next-intl
for routing and language detection, you need to set middleware
and navigation
. Create a src/middleware.ts
file if it does not exist. Add the following code in this file.
import createMiddleware from 'next-intl/middleware';
import { ALL_LANGUAGES, DEFAULT_LANGUAGE } from '@/tolgee/shared';
// read more about next-intl middleware configuration
// https://next-intl-docs.vercel.app/docs/routing/middleware#locale-prefix
export default createMiddleware({
locales: ALL_LANGUAGES,
defaultLocale: DEFAULT_LANGUAGE,
localePrefix: 'as-needed',
});
export const config = {
// Skip all paths that should not be internationalized
matcher: ['/((?!api|_next|.*\\..*).*)'],
};
Next, create a src/navigation.ts
file. This provides easy access to the navigation APIs in your components.
import { createSharedPathnamesNavigation } from 'next-intl/navigation';
import { ALL_LANGUAGES } from './tolgee/shared';
// read more about next-intl library
// https://next-intl-docs.vercel.app
export const { Link, redirect, usePathname, useRouter } =
createSharedPathnamesNavigation({ locales: ALL_LANGUAGES });
To gain a comprehensive understanding of how
next-intl
operates, read their documentation. This example utilizes the necessary setup for proper routing. Not all the listed configurations are required.
Update next.config.js
You also need to update the next.config.js
file as follows.
import createNextIntlPlugin from 'next-intl/plugin';
const withNextIntl = createNextIntlPlugin();
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default withNextIntl(nextConfig);
Add i18n/request.ts
file
The i18n/request.ts
is required by next-intl
package, we don't actually need it, so we are only doing necessary actions to stop next-intl
from complaining.
import { getRequestConfig } from 'next-intl/server';
import { getStaticData } from '../tolgee/shared';
export default getRequestConfig(async ({ locale }) => {
return {
// do this to make next-intl not emitting any warnings
messages: { locale },
};
});
Localizing Server components
Now that everything is setup, you can use the getTranslate
function to render the translated text. Since this is a server component, you use getTranslate
instead of the useTranslate
hook.
import { getTranslate } from '@/tolgee/server';
export default async function IndexPage() {
// because this is server component, use `getTranslate`
// not useTranslate from '@tolgee/react'
const t = await getTranslate();
return (
<main>
<h1>{t('hello_world')}</h1>
</main>
);
}
If everything is set up correctly, you could use in-context translation. Press and holde the alt
(or option
) key, and click hello_world
. This will open the in-context pop-up window.
Localizing Client components
For client components, you can use the useTranslate
hook or the t-component
.
'use client';
import { useTranslate } from '@tolgee/react';
export const ExampleClientComponent = () => {
const { t } = useTranslate();
return (
<section>
<span>{t('example-key-in-client-component')}</span>
</section>
);
};
Make sure to use @/tolgee/server
in server components and @tolgee/react
in client components.
Switching Languages
For switching languages you should use the next-intl
router helpers.
'use client';
import React, { ChangeEvent, useTransition } from 'react';
import { usePathname, useRouter } from '@/navigation';
import { useTolgee } from '@tolgee/react';
export const LangSelector: React.FC = () => {
const tolgee = useTolgee(['language']);
const locale = tolgee.getLanguage();
const router = useRouter();
const pathname = usePathname();
const [isPending, startTransition] = useTransition();
function onSelectChange(event: ChangeEvent<HTMLSelectElement>) {
const newLocale = event.target.value;
startTransition(() => {
router.replace(pathname, { locale: newLocale });
});
}
return (
<select onChange={onSelectChange} value={locale}>
<option value="en">🇬🇧 English</option>
<option value="cs">🇨🇿 Česky</option>
</select>
);
};
Make sure you use navigation-related components from @/navigation
instead natively from Next.js. This ensures that the correct locale is passed to the route.
Limitations of Server Components
Although in-context translation works with server components, there are some limitations compared to client components. The Tolgee cache on the server is separate. This prevents Tolgee from automatically changing the translation when creating a screenshot (unlike with client components, which swap the content if you've modified it in a dialog).
Furthermore, if you're using the Tolgee browser plugin, it won't affect the server's transition to dev mode. As a result, only the client switches, leaving server components non-editable in this mode.