You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fix(i18n): server-side locale detection to remove flash of default language (#132)
* fix(i18n): server-side locale detection to remove flash of default language
Closes#126.
When a user's preferred language was not the default `en` (e.g. `ar`),
the page first rendered in English from the server, then re-rendered in
Arabic on the client after `useEffect` finished detecting the locale via
`navigator.language` and `localStorage`. The result was a flash of
incorrect content plus a `<html lang/dir>` hydration mismatch.
The fix runs detection on the server using cookies + `Accept-Language`,
and the cookie is written by middleware so subsequent requests skip the
detection round-trip.
## Changes
- `middleware.ts` (new): on each request, if no valid `app-locale`
cookie exists, parse `Accept-Language` and set the cookie in the
response. Edge-safe; <1ms overhead per request.
- `lib/i18n-core.ts` (new): server- and edge-safe constants and helpers
(`supportedLocales`, `LOCALE_COOKIE`, `parseAcceptLanguage`,
`isSupportedLocale`, `getLocaleDir`, `localeMeta`). No React, no DOM,
so the middleware can import it.
- `app/layout.tsx`: read the cookie via `cookies()` then fall through to
`Accept-Language` via `headers()`. Set `<html lang>` and `<html dir>`
on the initial server render and pass `initialLocale` down.
- `app/providers.tsx`, `components/language-provider.tsx`: forward
`initialLocale` to `useI18nProvider`.
- `lib/i18n.ts`: the provider now seeds its initial state from
`initialLocale` instead of running detection inside `useState`. When
the user changes locale at runtime, both the cookie and localStorage
are updated so the next reload renders correctly without a flash.
Existing localStorage-stored preferences are still honored; the cookie
is written whenever the locale changes so the client-side state and
the server-side initial render converge over time.
## Verification
`npx tsc --noEmit` is clean.
* fix(i18n): respect Accept-Language q-values and scope middleware
Address codex review on #126:
- parseAcceptLanguage now parses q-values (default 1.0 per RFC 9110
§12.5.4), drops q=0 (explicit rejection), and selects the
highest-q supported language. Previously a header like
'en;q=0.1, ar;q=1' picked en because the loop scanned in
textual order and ignored q.
- middleware.ts now exports a matcher config that excludes
_next/static, _next/image, /api, common static asset extensions,
and crawl files. Asset and API responses no longer attach a
Set-Cookie header and remain cacheable.
Typecheck still clean.
---------
Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
0 commit comments