请求中获取浏览器推荐语言

Published: · LastMod: July 27, 2023 · 89 words

请求中获取浏览器推荐语言 🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let languages: string[] | undefined
// get locale from cookie
const localeCookie = request.cookies.get('locale')
languages = localeCookie?.value ? [localeCookie.value] : []

if (!languages.length) {
// Negotiator expects plain object so we need to transform headers
const negotiatorHeaders: Record<string, string> = {}
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value))
// Use negotiator and intl-localematcher to get best locale
languages = new Negotiator({ headers: negotiatorHeaders }).languages()
}