feat: add localization and site settings
This commit is contained in:
30
src/i18n/getLocale.ts
Normal file
30
src/i18n/getLocale.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
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<Locale> {
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user