Adding i18n
Adding Internationalization
Section titled “Adding Internationalization”Multi-language support with next-intl.
pnpm add next-intl
Translation Files
Section titled “Translation Files”apps/app/messages/en.json
:
{
"dashboard.title": "Dashboard",
"dashboard.welcome": "Welcome back, {name}!",
"tasks.createTask": "Create Task"
}
apps/app/messages/sv.json
:
{
"dashboard.title": "Instrumentpanel",
"dashboard.welcome": "Välkommen tillbaka, {name}!",
"tasks.createTask": "Skapa Uppgift"
}
Configuration
Section titled “Configuration”apps/app/i18n.ts
:
import { getRequestConfig } from "next-intl/server";
export const locales = ["en", "sv"] as const;
export default getRequestConfig(async ({ locale }) => ({
messages: (await import(`./messages/${locale}.json`)).default,
}));
Locale Routing
Section titled “Locale Routing”Rename app/
to app/[locale]/
and update layout:
import { NextIntlClientProvider } from "next-intl";
export default async function RootLayout({ children, params: { locale } }) {
const messages = await getMessages();
return (
<html lang={locale}>
<body>
<NextIntlClientProvider messages={messages}>
{children}
</NextIntlClientProvider>
</body>
</html>
);
}
import { useTranslations } from "next-intl";
export function Dashboard() {
const t = useTranslations("dashboard");
return <h1>{t("title")}</h1>;
}
Language Switcher
Section titled “Language Switcher”const locale = useLocale();
const router = useRouter();
<button onClick={() => router.push(`/${newLocale}${pathname}`)}>
{locale === "en" ? "English" : "Svenska"}
</button>
URLs: /en/dashboard
, /sv/dashboard