import { cookies, headers } from "next/headers"; import { DEFAULT_LOCALE, LOCALES, LOCALE_COOKIE, type Locale } from "./messages"; function isLocale(v: string | undefined | null): v is Locale { return !!v && (LOCALES as string[]).includes(v); } /** * Resolve the current locale on the server. * 1. Explicit cookie * 2. Accept-Language header (en* → en, otherwise zh) * 3. Default */ export async function getServerLocale(): Promise { const cookieStore = await cookies(); const cookieLocale = cookieStore.get(LOCALE_COOKIE)?.value; if (isLocale(cookieLocale)) return cookieLocale; try { const h = await headers(); const accept = h.get("accept-language") || ""; const first = accept.split(",")[0]?.trim().toLowerCase() || ""; if (first.startsWith("en")) return "en"; if (first.startsWith("zh")) return "zh"; } catch { // headers() can throw outside request scope } return DEFAULT_LOCALE; }