在 Next.js 中使用 Langsys
各处的模式都相同:服务器只获取一次目录(写入密钥保留在服务器端),客户端则使用只读密钥,基于该预置数据初始化 langsys-js-react,无需重复获取。翻译本身在浏览器中完成:服务器发送的 HTML 使用基础语言,这也是搜索引擎所索引的内容,页面在加载时会切换为访问者的语言。
1 · 在服务器上获取目录
服务端组件使用原生 fetch 获取目录,服务端不需要 SDK。写入密钥保留在服务端,客户端获得的是只读密钥。两部分看到的是同一个目录,客户端只是跳过了首次获取。
// app/layout.tsx (Server Component)
import type { iCategories } from 'langsys-js-react';
import { LangsysClient } from './LangsysClient';
async function getTranslations(locale: string): Promise<iCategories> {
const res = await fetch(
`https://api.langsys.dev/api/projects/${process.env.LANGSYS_PROJECT_ID}/translations?locale=${locale}`,
{ headers: { 'x-Authorization': process.env.LANGSYS_API_KEY! } }
);
const result = await res.json();
return result.data as iCategories;
}
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const locale = 'en-US'; // from cookie / Accept-Language / route segment
const translations = await getTranslations(locale);
return (
<html lang={locale}>
<body>
<LangsysClient
locale={locale}
translations={translations}
projectId={process.env.LANGSYS_PROJECT_ID!}
apiKey={process.env.NEXT_PUBLIC_LANGSYS_API_KEY!} // read-only
>
{children}
</LangsysClient>
</body>
</html>
);
} 2 · 在客户端初始化
一个小型的 'use client' 封装组件会在浏览器中使用预置的词库初始化 SDK,因此启动时无需获取任何数据。该效果运行时,文本会从基础语言切换为访客的语言。
// app/LangsysClient.tsx
'use client';
import { useEffect, type ReactNode } from 'react';
import { LangsysApp, useLocaleStore, type iCategories } from 'langsys-js-react';
export function LangsysClient(props: {
locale: string;
translations: iCategories;
projectId: string;
apiKey: string;
children: ReactNode;
}) {
const [, , localeStore] = useLocaleStore(props.locale);
useEffect(() => {
LangsysApp.init({
projectid: props.projectId,
key: props.apiKey,
UserLocaleStore: localeStore,
initialTranslations: props.translations,
initialTranslationsLocale: props.locale,
ssrTokenStrategy: 'client',
});
}, [localeStore, props.projectId, props.apiKey, props.translations, props.locale]);
return <>{props.children}</>;
} 3 · 在下方任意位置使用
从这里开始,它就是普通的 React SDK:在任意客户端组件中使用 useT(),并通过同一个存储切换语言区域。应用中只保留一个语言区域存储(在您调用 init 的位置创建),并将 setLocale 向下传递,而不要在互不相关的组件树中创建新的存储。
'use client';
import { useT } from 'langsys-js-react';
export function Hero() {
const t = useT();
return <h1>{t('Welcome to our store', 'Home')}</h1>;
}