Now, go to src/app/[locale]/layout.tsx
, you will notice this:
export async function generateStaticParams() {
return config.i18n.locales.map((locale) => ({ locale }));
}
What this does, as per the docs, is that it generates the static params for the [locale]
route segment. This is required if you want to use the app as a static site.
Then, scroll down and you will see this:
export async function generateMetadata(props: LayoutProps): Promise<Metadata> {
const { locale } = await props.params;
const t = await getTranslations({ locale, namespace: "metadata" });
return {
title: t("title"),
description: t("description"),
};
}
Ignore everything, and focus on the getTranslations
call. If you want translations on the server side, this is what you need to call.
locale
is the current locale.namespace
is the namespace you want to get the translations from.
You can learn more about namespaces here.
Then, scroll down and find this:
export default async function LocaleLayout({ params, children }: LayoutProps) {
const { locale } = await params;
const direction = getLangDir(locale);
// Ensure that the incoming `locale` is valid
if (!routing.locales.includes(locale as any)) {
notFound();
}
// Enable static rendering
setRequestLocale(locale);
// Providing all messages to the client side is the easiest way to get started
const messages = await getMessages();
return (
<html lang={locale}>
<body {...}>
<NextIntlClientProvider messages={messages}>
...
</NextIntlClientProvider>
</body>
</html>
);
}
There's a lot happening here, let's break it down.
- We get the locale from the params.
- We get the direction of the locale using the
getLangDir
helper from thertl-detect
package. - We ensure that the incoming
locale
is valid. If it's not, we callnotFound()
. Since this layout wraps the entire app, this validation goes all the way down to every single page in the app. - We set the locale using
setRequestLocale
. This is necessary for next-intl to know which locale to use when rendering statically. - We get the messages for the current locale.
Then, we wrap the entire app in the NextIntlClientProvider
. This is necessary for the app to be able to switch locales on the client side.
On the client, you can simply call the useTranslations
hook, for example:
const t = useTranslations("common");
This is used in the src/app/[locale]/rq/users/[id]/page.tsx
file.
If you, for whatever reason, need the locale on the client side, you can either use the useLocale
from next-intl
or the useParams
from Next.js.
That's all there is to it! You have an app that supports i18n out of the box.