import { internationalization } from '@intlayer/config/built'; import { DEFAULT_LOCALE } from '@intlayer/config/defaultValues'; import { localeDetector } from '@intlayer/core/localization'; import { getLocaleFromStorageServer } from '@intlayer/core/utils'; import type { Locale } from '@intlayer/types/allLocales'; // Helper function to extract locale from headers/cookies /** * Helper function to extract the current locale from Next.js headers and cookies. * * This function is designed to be used in Server Components, Server Actions, or Route Handlers * to determine the locale preferred by the user or stored in their preferences. * * @returns A promise that resolves to the detected `Locale`. * * @example * ```tsx * import { getLocale } from 'next-intlayer/server'; * * export default async function MyServerComponent() { * const locale = await getLocale(); * // ... * } * ``` */ export const getLocale = async (): Promise => { const defaultLocale = internationalization?.defaultLocale ?? DEFAULT_LOCALE; // Loaded lazily: `next/headers` creates Next.js request storages on load, // which breaks a custom server that imports `withIntlayer` (same entry) // before Next.js has set up `AsyncLocalStorage`. const { cookies, headers } = await import('next/headers.js'); // Try locale from header const headersList = await headers(); const cookiesList = await cookies(); const storedLocale = getLocaleFromStorageServer({ getCookie: (name: string) => cookiesList.get(name)?.value ?? null, getHeader: (name: string) => headersList.get(name) ?? null, }); if (storedLocale) return storedLocale as Locale; // Fallback to Accept-Language negotiation const negotiatorHeaders: Record = {}; headersList.forEach((value, key) => { negotiatorHeaders[key] = value; }); const userFallbackLocale = localeDetector(negotiatorHeaders); if (userFallbackLocale) return userFallbackLocale as Locale; // Default locale return defaultLocale; };