优化多语言处理

This commit is contained in:
xintaofei
2026-03-07 21:09:55 +08:00
parent 3cc28167e0
commit 8f265f8c0c
6 changed files with 193 additions and 36 deletions

View File

@@ -1,7 +1,13 @@
import { getRequestConfig } from "next-intl/server"
import enMessages from "@/i18n/messages/en.json"
import { getMessagesForLocale } from "@/i18n/messages"
import { resolveRequestLocale } from "@/i18n/resolve-request-locale"
import { APP_LOCALE_TO_INTL_LOCALE } from "@/lib/i18n"
export default getRequestConfig(async () => ({
locale: "en",
messages: enMessages,
}))
export default getRequestConfig(async () => {
const appLocale = await resolveRequestLocale()
return {
locale: APP_LOCALE_TO_INTL_LOCALE[appLocale],
messages: await getMessagesForLocale(appLocale),
}
})

View File

@@ -0,0 +1,51 @@
import { cookies, headers } from "next/headers"
import {
LANGUAGE_COOKIE_KEY,
LANGUAGE_MODE_COOKIE_KEY,
parseAcceptLanguageHeader,
parseLocaleFromCookieValue,
resolveSystemLocale,
} from "@/lib/i18n"
import type { AppLocale, LanguageMode } from "@/lib/types"
const FALLBACK_LOCALE: AppLocale = "en"
function parseLanguageModeCookie(value: string | undefined): LanguageMode {
return value === "manual" ? "manual" : "system"
}
export async function resolveRequestLocale(): Promise<AppLocale> {
let configuredLocale: AppLocale | null = null
let languageMode: LanguageMode = "system"
try {
const cookieStore = await cookies()
configuredLocale = parseLocaleFromCookieValue(
cookieStore.get(LANGUAGE_COOKIE_KEY)?.value
)
languageMode = parseLanguageModeCookie(
cookieStore.get(LANGUAGE_MODE_COOKIE_KEY)?.value
)
} catch {
// Ignore when request cookies are unavailable (e.g. static export build).
}
if (configuredLocale && languageMode === "manual") {
return configuredLocale
}
try {
const headerStore = await headers()
const candidates = parseAcceptLanguageHeader(
headerStore.get("accept-language")
)
const fromHeader = resolveSystemLocale(candidates)
if (fromHeader) {
return fromHeader
}
} catch {
// Ignore when request headers are unavailable (e.g. static export build).
}
return configuredLocale ?? FALLBACK_LOCALE
}