feat(i18n): add locale management and configuration

This commit is contained in:
cfngc4594 2025-04-14 23:15:41 +08:00
parent 30922a25bb
commit d98522d643
3 changed files with 51 additions and 0 deletions

9
src/config/i18n.ts Normal file
View File

@ -0,0 +1,9 @@
// Supported locales
export const locales = ["en", "zh"] as const;
export type Locale = (typeof locales)[number];
// Default locale
export const defaultLocale: Locale = "en";
// Cookie key for storing selected locale
export const LOCALE_COOKIE_NAME = "LOCALE";

31
src/i18n/locale.ts Normal file
View File

@ -0,0 +1,31 @@
"use server";
import {
defaultLocale,
Locale,
LOCALE_COOKIE_NAME,
locales
} from "@/config/i18n";
import { cookies, headers } from "next/headers";
export async function getUserLocale() {
const cookieLocale = (await cookies()).get(LOCALE_COOKIE_NAME)?.value;
if (cookieLocale && locales.includes(cookieLocale as Locale)) {
return cookieLocale as Locale;
}
const acceptLanguage = (await headers()).get("accept-language") || "";
const firstLang = acceptLanguage.split(",")[0]?.trim().toLowerCase();
const langPrefix = firstLang?.slice(0, 2);
if (locales.includes(langPrefix as Locale)) {
return langPrefix as Locale;
}
return defaultLocale;
}
export async function setUserLocale(locale: Locale) {
(await cookies()).set(LOCALE_COOKIE_NAME, locale);
}

11
src/i18n/request.ts Normal file
View File

@ -0,0 +1,11 @@
import { getUserLocale } from '@/i18n/locale';
import { getRequestConfig } from 'next-intl/server';
export default getRequestConfig(async () => {
const locale = await getUserLocale();
return {
locale,
messages: (await import(`../../messages/${locale}.json`)).default
};
});