| 160 | * Gets the locale from the NEXT_LOCALE cookie |
| 161 | */ |
| 162 | export function getCookieLocale( |
| 163 | cookieHeader: string | undefined, |
| 164 | locales: string[] |
| 165 | ): string | undefined { |
| 166 | if (!cookieHeader || !locales.length) { |
| 167 | return undefined |
| 168 | } |
| 169 | |
| 170 | try { |
| 171 | const cookies = cookieHeader.split(';').reduce( |
| 172 | (acc, cookie) => { |
| 173 | const [key, ...valueParts] = cookie.trim().split('=') |
| 174 | if (key && valueParts.length > 0) { |
| 175 | acc[key] = decodeURIComponent(valueParts.join('=')) |
| 176 | } |
| 177 | return acc |
| 178 | }, |
| 179 | {} as Record<string, string> |
| 180 | ) |
| 181 | |
| 182 | const nextLocale = cookies.NEXT_LOCALE?.toLowerCase() |
| 183 | if (!nextLocale) { |
| 184 | return undefined |
| 185 | } |
| 186 | |
| 187 | return locales.find((locale) => locale.toLowerCase() === nextLocale) |
| 188 | } catch (err) { |
| 189 | return undefined |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | /** |
| 194 | * Detects the appropriate locale based on path, domain, cookie, and accept-language |