React Server Components
Magic Translate fully supports React Server Components. Content is translated on the server, so search engines and users get translated HTML without any client-side JavaScript.
Installation
# using npmnpm i @magic-translate/react-ssr# using yarnyarn add @magic-translate/react-ssr# using pnpmpnpm add @magic-translate/react-ssr
Setup
Set up the translate function once, for example in lib/translate.ts. Keep your API key in an environment variable.
import { setupT } from '@magic-translate/react-ssr';export const translate = setupT({apiKey: process.env.MAGIC_TRANSLATE_API_KEY!});
If you don't have an API key yet, sign up for Magic Translate to get one.
Translating a server component
createLocalizedT binds the translate function to one language and returns the <T> component and the t() function. It accepts a Language or any locale such as de or pt-BR.
import { createLocalizedT } from '@magic-translate/react-ssr';import { translate } from '@/lib/translate';export default async function AboutPage() {const { T, t } = createLocalizedT(translate, 'de');return (<article><h1><T>About us</T></h1><img src="/team.jpg" alt={await t('Our team in Zurich')} /></article>);}
Because every page shares the same translate function, translations are batched and cached across your whole app.
For a single component, createServerT sets everything up in one call. It caches only within that call.
import { createServerT } from '@magic-translate/react-ssr';const { T } = createServerT({apiKey: process.env.MAGIC_TRANSLATE_API_KEY!,locale: 'zh'});
The
<T>component from React SSR only works in React Server Components. In client components, use the React client instead.
Choosing the language per component
createT returns a <T> component that takes the language as a prop. This is useful when the language differs from component to component.
import { createT, Language } from '@magic-translate/react-ssr';import { translate } from '@/lib/translate';const T = createT(translate);const Greeting = async () => <T lang={Language.ZH}>Please translate me!</T>;
All <T> components accept the same options as the client <T> component, such as formality.
Example project
You can find an example SSR project on GitHub.