Files
HealthLog/src/lib/i18n/resolve-initial-locale.ts
T
Marc-André Bombeck e9692f0b81 fix(i18n): survive Safari's 7-day cookie cap on the chosen locale
The first-paint ladder consulted only the healthlog-locale cookie and
Accept-Language — never User.locale. The cookie is written client-side
via document.cookie, which Safari ITP caps at 7 days, so a chosen
language silently reverted to the browser language once a week.

Three seams close it:
- resolveInitialLocale (extracted to src/lib/i18n/resolve-initial-locale.ts)
  now reads User.locale on a cookie miss via a lightweight session read
  (no sliding-expiry write, no cookie mutation, fail-soft) before the
  Accept-Language fallback.
- PUT /api/auth/me/locale mirrors the accepted locale into the cookie
  via Set-Cookie (365 days, SameSite=Lax, not HttpOnly, Secure via
  shouldEmitSecureCookie) — server-set cookies are exempt from the ITP
  cap, and the mount-time backfill hitting the route doubles as the
  weekly refresh.
- getSession re-emits the cookie when the user has a persisted locale
  but the cookie is absent (absent-only, so a mid-switch cookie is
  never reverted before the PUT lands).

Users who never chose a language stay on Accept-Language.
2026-07-05 21:01:50 +02:00

48 lines
1.8 KiB
TypeScript

import { headers, cookies } from "next/headers";
import { parseLocaleFromAcceptLanguage } from "@/lib/format-locale";
import { locales, type Locale } from "@/lib/i18n/config";
import { LOCALE_COOKIE } from "@/lib/i18n/locale-cookie";
import { getSessionUserLocale } from "@/lib/auth/session";
/**
* First-paint locale ladder for the root layout:
*
* 1. `healthlog-locale` cookie — the SSR handoff the client writes on
* every switch and the server re-emits on session touch.
* 2. `User.locale` — the persisted preference. Consulted only on a
* cookie miss (Safari ITP expires the script-written cookie after
* 7 days; without this step the app fell back to the browser
* language once a week even though the user had chosen one).
* 3. Accept-Language — users who never chose stay on the browser
* language ("automatic").
*
* Fail-soft throughout: cookies()/headers() can throw
* (DynamicServerError, …) and the session read can hit a DB hiccup — a
* locale resolution problem must never crash the root layout into
* global-error.tsx.
*/
export async function resolveInitialLocale(): Promise<Locale> {
try {
const cookieStore = await cookies();
const cookieLocale = cookieStore.get(LOCALE_COOKIE)?.value;
if (cookieLocale && (locales as readonly string[]).includes(cookieLocale)) {
return cookieLocale as Locale;
}
let userLocale: string | null = null;
try {
userLocale = await getSessionUserLocale();
} catch {
// DB hiccup — fall through to Accept-Language rather than "en".
}
if (userLocale && (locales as readonly string[]).includes(userLocale)) {
return userLocale as Locale;
}
const headerList = await headers();
return parseLocaleFromAcceptLanguage(headerList.get("accept-language"));
} catch {
return "en";
}
}