核心价值依据用户语言偏好协商内容与路由,提升国际化体验与一致性。使用 `Vary: Accept-Language` 与 `Content-Language` 保持缓存与客户端行为正确。语言解析与响应export const runtime = 'edge' const supported = ['zh-CN', 'en', 'ja'] function pick(accept: string): string { const parts = accept.split(',').map(s => s.trim()) for (const p of parts) { const lang = p.split(';')[0] if (supported.includes(lang)) return lang const base = lang.split('-')[0] if (supported.includes(base)) return base } return 'en' } export async function GET(req: Request) { const al = req.headers.get('accept-language') || '' const cookie = req.headers.get('cookie') || '' const match = /lang=([^;]+)/.exec(cookie) const lang = match ? match[1] : pick(al) const body = JSON.stringify({ message: lang === 'zh-CN' ? '你好' : lang === 'ja' ? 'こんにちは' : 'Hello' }) return new Response(body, { headers: { 'Content-Type': 'application/json; charset=utf-8', 'Content-Language': lang, 'Vary': 'Accept-Language', 'Cache-Control': 'public, max-age=60', 'Set-Cookie': `lang=${lang}; Path=/; SameSite=Lax`, }, }) } 路由重定向示例import { NextResponse } from 'next/server' export function middleware(req: Request) { const url = new URL((req as any).url) const al = (req as any).headers.get('accept-language') || '' if (url.pathname === '/') { const lang = pick(al) url.pathname = `/${lang}` return NextResponse.redirect(url) } return NextResponse.next() } 结论使用 Accept-Language 与 Cookie 记忆协商语言并治理缓存头,可在多语言场景下获得更稳定与一致的用户体验。

发表评论 取消回复