Dynamic content
Translate content from a CMS, an API or your users, server-side.
The plugin only translates text written in your code. Content it never sees, such as a CMS body, a search result or a user's own words, is translated server-side during the render, with the functions of @weglot/translate-react/dynamic:
tDynamic(text)
One text.
tDynamicAll(texts)
Several texts, in one request.
tDynamicHtml(html)
An HTML fragment, keeping its inline markup.
These functions only run server-side, in Next.js server components: they use your API key to call the Weglot API and read the visitor's language from the request. They read the languages from the plugin, so the plugin must be installed as described in Getting started.
Each function expects a string: pass ?? "" for fields that can be empty. Start the calls of a page together, with Promise.all, so they share one request:
// app/blog/[slug]/page.tsx
import { tDynamic, tDynamicHtml } from "@weglot/translate-react/dynamic";
export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const post = await getPost(slug);
const [title, body] = await Promise.all([
tDynamic(post.title ?? ""),
tDynamicHtml(post.body ?? ""),
]);
return (
<article>
<h1>{title}</h1>
<div dangerouslySetInnerHTML={{ __html: body }} />
</article>
);
}Translate SEO fields in generateMetadata the same way:
When the source text is returned
A slow call never holds up your page. These functions return the source text:
When the API takes longer than 500 ms. Calls started together are batched into one request, which shares this timeout. A call awaited after another one waits for its own request.
The first time a text is requested. Weglot generates the translation, and later requests get it.
Options
Each function accepts options as its last argument:
timeoutMs: how long to wait for the API, in milliseconds (default500).locale: translate to this language instead of the visitor's.
If your API key does not come from the WEGLOT_API_KEY environment variable, set it once with configureDynamicTranslation({ apiKey }).
Last updated