server.ts - 服务端国际化
概述
提供服务端语言切换功能,支持 Server Actions 和用户登录时的语言同步。
函数
setLocaleServer
export async function setLocaleServer(locale: string): Promise<void>
设置用户的语言偏好(服务端动作)。
功能:
- 验证语言是否在支持列表中
- 设置 Cookie(有效期1年)
- 如用户已登录,将语言偏好保存到数据库
参数:
locale: 目标语言代码
异常:
- 如果语言不受支持,抛出
Error
示例:
"use server";
import { setLocaleServer } from '@/lib/i18n/server';
// 在 Server Action 中使用
export async function changeUserLocale(formData: FormData) {
const locale = formData.get('locale') as string;
await setLocaleServer(locale);
}
syncLocaleFromUser
export async function syncLocaleFromUser(userId: string): Promise<void>
用户登录时,将数据库中的语言偏好同步到 Cookie。
功能:
- 从数据库查询用户的语言偏好
- 如存在,设置到 Cookie
参数:
userId: 用户ID
使用场景:
- 用户登录回调中
- 从其他设备同步语言偏好
示例:
import { syncLocaleFromUser } from '@/lib/i18n/server';
import { auth } from '@/lib/auth';
// 在登录回调中
export async function handleLogin() {
const session = await auth();
if (session?.user?.id) {
await syncLocaleFromUser(session.user.id);
}
}
与客户端的区别
| 特性 | 客户端 (client.ts) | 服务端 (server.ts) |
|---|---|---|
| 执行环境 | 浏览器 | 服务器 |
| 数据库同步 | 不支持 | 支持 |
| 语言验证 | 否 | 是 |
| 页面刷新 | 自动 | 需手动处理 |
安全考虑
- 服务端函数验证语言是否在支持列表中,防止非法输入
- Cookie 设置使用
sameSite: "lax",防止 CSRF 攻击