Documentation

Next.js

Magic Translate works with both routers of Next.js. With the App Router, pages are translated on the server, so every language gets its own fully translated HTML for search engines.

App Router

Put your pages under a [locale] segment and list the languages you want to offer.

// app/[locale]/layout.tsx
const locales = ['en', 'de', 'fr', 'ja'];
export function generateStaticParams() {
return locales.map((locale) => ({ locale }));
}
export default async function LocaleLayout({
children,
params
}: {
children: React.ReactNode;
params: Promise<{ locale: string }>;
}) {
const { locale } = await params;
return (
<html lang={locale}>
<body>{children}</body>
</html>
);
}

Then translate your pages with React SSR, using the locale parameter as the language.

// app/[locale]/page.tsx
import { createLocalizedT } from '@magic-translate/react-ssr';
import { translate } from '@/lib/translate';
export default async function HomePage({
params
}: {
params: Promise<{ locale: string }>;
}) {
const { locale } = await params;
const { T } = createLocalizedT(translate, locale);
return (
<h1>
<T>Welcome to our website</T>
</h1>
);
}

Page titles and descriptions are translated with the translate function.

Client components that need translations, such as interactive menus, can use the React client. Wrap them in a MagicTranslateProvider and convert the locale with utsLocaleToLanguage.

'use client';
import {
MagicTranslateProvider,
utsLocaleToLanguage
} from '@magic-translate/react';
export function Providers({
locale,
children
}: {
locale: string;
children: React.ReactNode;
}) {
return (
<MagicTranslateProvider
apiKey={process.env.NEXT_PUBLIC_MAGIC_TRANSLATE_API_KEY!}
language={utsLocaleToLanguage(locale)}
>
{children}
</MagicTranslateProvider>
);
}

Pages Router

First set up your locales by following the Next.js internationalization guide.

Then pass the locale Next.js determined to the MagicTranslateProvider. Magic Translate's language codes don't map 1:1 to the locales Next.js uses, so convert them with utsLocaleToLanguage.

// pages/_app.tsx
import type { AppProps } from 'next/app';
import { useRouter } from 'next/router';
import {
MagicTranslateProvider,
utsLocaleToLanguage
} from '@magic-translate/react';
export default function MyApp({ Component, pageProps }: AppProps) {
const { locale } = useRouter();
return (
<MagicTranslateProvider
apiKey="<your-api-key>"
language={utsLocaleToLanguage(locale)}
>
<Component {...pageProps} />
</MagicTranslateProvider>
);
}

Your website is now translated based on the locale Next.js determines.