Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

fix: select the default language from the user's locale (#144)

夜浮卿a337192e4315
diff --git a/apps/api/src/__tests__/helpers/app.ts b/apps/api/src/__tests__/helpers/app.ts
index c30539b3..24c25e8a 100644
--- a/apps/api/src/__tests__/helpers/app.ts
+++ b/apps/api/src/__tests__/helpers/app.ts
@@ -5,10 +5,10 @@ import { app } from '../../app';
// Use for unauthenticated routes; planner routes return 401 through this.
export const api = treaty(app);
-// Treaty client that sends a session cookie on every request. Pass the `cookie`
-// from signUpTestUser to act as that user.
-export function authedApi(cookie: string) {
- return treaty(app, { headers: { cookie } });
+// Treaty client that sends a session cookie on every request. Pass additional
+// headers when the route behavior depends on request metadata.
+export function authedApi(cookie: string, headers?: Record<string, string>) {
+ return treaty(app, { headers: { ...headers, cookie } });
}
export type Api = typeof api;
diff --git a/apps/api/src/user-preferences/__tests__/integration/user-preferences.test.ts b/apps/api/src/modules/user-preferences/__tests__/integration/user-preferences.test.ts
similarity index 83%
rename from apps/api/src/user-preferences/__tests__/integration/user-preferences.test.ts
rename to apps/api/src/modules/user-preferences/__tests__/integration/user-preferences.test.ts
index b0e1d3e6..dbfb1976 100644
--- a/apps/api/src/user-preferences/__tests__/integration/user-preferences.test.ts
+++ b/apps/api/src/modules/user-preferences/__tests__/integration/user-preferences.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { api, authedApi } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { api, authedApi } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
// Account preferences are self-scoped: a user only ever reads and writes their own
// row, so there is no project or permission wiring to cover. A read before any write
@@ -32,6 +32,29 @@ describe('user preferences', () => {
});
});
+ it('uses the preferred supported browser language when nothing was saved', async () => {
+ const u = await signUpTestUser();
+
+ const res = await authedApi(u.cookie, {
+ 'accept-language': 'ru;q=0.4,zh-CN;q=0.9,en;q=0.8',
+ }).account.preferences.get();
+
+ expect(res.status).toBe(200);
+ expect(res.data?.locale).toBe('zh-CN');
+ });
+
+ it('saves the preferred browser language with the first preference update', async () => {
+ const u = await signUpTestUser();
+ const client = authedApi(u.cookie, {
+ 'accept-language': 'uk-UA,uk;q=0.9,en;q=0.8',
+ });
+
+ await client.account.preferences.patch({ theme: 'dark' });
+
+ const stored = await authedApi(u.cookie, { 'accept-language': 'en' }).account.preferences.get();
+ expect(stored.data).toMatchObject({ locale: 'uk', theme: 'dark' });
+ });
+
it('saves a full update and reads it back', async () => {
const u = await signUpTestUser();
const client = authedApi(u.cookie);
diff --git a/apps/api/src/modules/user-preferences/__tests__/unit/locale.test.ts b/apps/api/src/modules/user-preferences/__tests__/unit/locale.test.ts
new file mode 100644
index 00000000..eb9dd70c
--- /dev/null
+++ b/apps/api/src/modules/user-preferences/__tests__/unit/locale.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'bun:test';
+import { localeFromAcceptLanguage } from '../../locale';
+
+describe('localeFromAcceptLanguage', () => {
+ it('uses the preferred supported language', () => {
+ expect(localeFromAcceptLanguage('ru;q=0.4,zh-CN;q=0.9,en;q=0.8')).toBe('zh-CN');
+ });
+
+ it('matches a supported base language to a regional browser locale', () => {
+ expect(localeFromAcceptLanguage('uk-UA,uk;q=0.9,en;q=0.8')).toBe('uk');
+ });
+
+ it('uses the fallback for a preferred wildcard', () => {
+ expect(localeFromAcceptLanguage('de-DE,*;q=0.9,zh;q=0.8')).toBe('en');
+ });
+
+ it('falls back to English when no requested language is supported', () => {
+ expect(localeFromAcceptLanguage('de-DE,fr;q=0.9')).toBe('en');
+ });
+});
diff --git a/apps/api/src/modules/user-preferences/index.ts b/apps/api/src/modules/user-preferences/index.ts
new file mode 100644
index 00000000..a23497e5
--- /dev/null
+++ b/apps/api/src/modules/user-preferences/index.ts
@@ -0,0 +1,68 @@
+import { Elysia } from 'elysia';
+import { requireUser } from '#shared/access';
+import { authContext } from '#shared/auth-context';
+import { HttpError } from '#shared/lib';
+import { errors } from '#shared/responses';
+import { getMembership } from '../../members/store';
+import { PreferencePatch, PreferenceResponse } from './model';
+import { getPreferences, isValidTimezone, updatePreferences } from './service';
+import { localeFromAcceptLanguage } from './locale';
+
+// The session user's own interface preferences: timezone, language, theme, how a clicked issue
+// opens, which section the app root lands on, whether the floating AI chat starts
+// visible, how an issue's status stats section starts out, whether they are
+// subscribed to the issues they touch, and the project they were in last. Every
+// route is self-scoped to the session user, so no project guard applies — a user
+// only ever reads or writes their own row. Not MCP tools: an agent has no business
+// changing a person's UI settings.
+export const userPreferenceRoutes = new Elysia({
+ name: 'user-preferences',
+ detail: { tags: ['Settings'] },
+})
+ .use(authContext)
+
+ .get(
+ '/account/preferences',
+ ({ user, request }) =>
+ getPreferences(
+ requireUser(user).id,
+ localeFromAcceptLanguage(request.headers.get('accept-language')),
+ ),
+ {
+ response: { 200: PreferenceResponse, ...errors(401) },
+ detail: {
+ summary: 'Get account preferences',
+ description:
+ "Get the current user's interface preferences. Returns browser-localized defaults when none were saved.",
+ },
+ },
+ )
+
+ .patch(
+ '/account/preferences',
+ async ({ user, body, request }) => {
+ const current = requireUser(user);
+ if (body.timezone !== undefined && !isValidTimezone(body.timezone)) {
+ throw new HttpError(400, 'Unknown timezone');
+ }
+ // Only a project the user belongs to can be remembered, so the stored id can
+ // never point at one they cannot open.
+ if (body.lastProjectId != null && !(await getMembership(body.lastProjectId, current.id))) {
+ throw new HttpError(403, 'You do not have access to this project');
+ }
+ return updatePreferences(
+ current.id,
+ body,
+ localeFromAcceptLanguage(request.headers.get('accept-language')),
+ );
+ },
+ {
+ body: PreferencePatch,
+ response: { 200: PreferenceResponse, ...errors(400, 401, 403) },
+ detail: {
+ summary: 'Update account preferences',
+ description:
+ "Update the current user's interface preferences. Omitted fields keep their current value.",
+ },
+ },
+ );
diff --git a/apps/api/src/modules/user-preferences/locale.ts b/apps/api/src/modules/user-preferences/locale.ts
new file mode 100644
index 00000000..0b817740
--- /dev/null
+++ b/apps/api/src/modules/user-preferences/locale.ts
@@ -0,0 +1,36 @@
+export const LOCALES = ['en', 'uk', 'ru', 'zh-CN'] as const;
+
+export type Locale = (typeof LOCALES)[number];
+
+export const DEFAULT_LOCALE: Locale = 'en';
+
+// Keep this matcher aligned with the Web copy so the first server render and
+// an account without saved preferences resolve to the same language.
+export function localeFromAcceptLanguage(value: string | null): Locale {
+ const requested = (value ?? '')
+ .split(',')
+ .map((part, index) => {
+ const [tag, ...parameters] = part.trim().split(';');
+ const qualityValue = parameters
+ .map((parameter) => parameter.trim().toLowerCase())
+ .find((parameter) => parameter.startsWith('q='))
+ ?.slice(2);
+ const quality = qualityValue === undefined ? 1 : Number(qualityValue);
+ return { tag: tag.toLowerCase(), quality, index };
+ })
+ .filter(({ tag, quality }) => tag && quality > 0 && quality <= 1)
+ .sort((a, b) => b.quality - a.quality || a.index - b.index);
+
+ for (const { tag } of requested) {
+ if (tag === '*') return DEFAULT_LOCALE;
+
+ const exact = LOCALES.find((locale) => locale.toLowerCase() === tag);
+ if (exact) return exact;
+
+ const language = tag.split('-')[0];
+ const sameLanguage = LOCALES.find((locale) => locale.toLowerCase().split('-')[0] === language);
+ if (sameLanguage) return sameLanguage;
+ }
+
+ return DEFAULT_LOCALE;
+}
diff --git a/apps/api/src/modules/user-preferences/model.ts b/apps/api/src/modules/user-preferences/model.ts
new file mode 100644
index 00000000..6956c0cb
--- /dev/null
+++ b/apps/api/src/modules/user-preferences/model.ts
@@ -0,0 +1,45 @@
+import { t } from 'elysia';
+import { HotkeyCombosSchema } from '../../settings/hotkeys';
+
+const Locale = t.Union([t.Literal('en'), t.Literal('uk'), t.Literal('ru'), t.Literal('zh-CN')]);
+const Theme = t.Union([t.Literal('light'), t.Literal('dark'), t.Literal('system')]);
+const IssueOpenMode = t.Union([t.Literal('panel'), t.Literal('page')]);
+const StartPage = t.Union([
+ t.Literal('inbox'),
+ t.Literal('dashboard'),
+ t.Literal('work-items'),
+ t.Literal('initiatives'),
+ t.Literal('ai-chat'),
+]);
+const IssueStatsView = t.Union([t.Literal('compact'), t.Literal('timeline')]);
+const IssueActivityView = t.Union([t.Literal('flat'), t.Literal('grouped')]);
+
+export const PreferenceResponse = t.Object({
+ timezone: t.String(),
+ locale: Locale,
+ theme: Theme,
+ issueOpenMode: IssueOpenMode,
+ startPage: StartPage,
+ showChatByDefault: t.Boolean(),
+ issueStatsOpen: t.Boolean(),
+ issueStatsView: IssueStatsView,
+ issueActivityView: IssueActivityView,
+ autoWatch: t.Boolean(),
+ lastProjectId: t.Nullable(t.Number()),
+ hotkeys: HotkeyCombosSchema,
+});
+
+export const PreferencePatch = t.Object({
+ timezone: t.Optional(t.String({ minLength: 1, maxLength: 64 })),
+ locale: t.Optional(Locale),
+ theme: t.Optional(Theme),
+ issueOpenMode: t.Optional(IssueOpenMode),
+ startPage: t.Optional(StartPage),
+ showChatByDefault: t.Optional(t.Boolean()),
+ issueStatsOpen: t.Optional(t.Boolean()),
+ issueStatsView: t.Optional(IssueStatsView),
+ issueActivityView: t.Optional(IssueActivityView),
+ autoWatch: t.Optional(t.Boolean()),
+ lastProjectId: t.Optional(t.Nullable(t.Number())),
+ hotkeys: t.Optional(HotkeyCombosSchema),
+});
diff --git a/apps/api/src/user-preferences/store.ts b/apps/api/src/modules/user-preferences/service.ts
similarity index 88%
rename from apps/api/src/user-preferences/store.ts
rename to apps/api/src/modules/user-preferences/service.ts
index 6fb767ca..314a9254 100644
--- a/apps/api/src/user-preferences/store.ts
+++ b/apps/api/src/modules/user-preferences/service.ts
@@ -1,19 +1,18 @@
import { db, userPreference } from '@repo/db';
import { eq, sql } from 'drizzle-orm';
+import { DEFAULT_LOCALE, type Locale } from './locale';
// A user's own interface preferences, held per account so the same choices apply on
// every device. One row per user; absent means nothing was changed yet and the
-// defaults below apply, so a read never fails. Timestamps stay UTC everywhere in the
-// API — `timezone` only tells the web app which zone to render them in.
+// request's browser-localized defaults apply, so a read never fails. Timestamps stay
+// UTC everywhere in the API — `timezone` only tells the web app which zone to render them in.
-export const LOCALES = ['en', 'uk', 'ru', 'zh-CN'] as const;
export const THEMES = ['light', 'dark', 'system'] as const;
export const ISSUE_OPEN_MODES = ['panel', 'page'] as const;
export const START_PAGES = ['inbox', 'dashboard', 'work-items', 'initiatives', 'ai-chat'] as const;
export const ISSUE_STATS_VIEWS = ['compact', 'timeline'] as const;
export const ISSUE_ACTIVITY_VIEWS = ['flat', 'grouped'] as const;
-export type Locale = (typeof LOCALES)[number];
export type Theme = (typeof THEMES)[number];
export type IssueOpenMode = (typeof ISSUE_OPEN_MODES)[number];
export type StartPage = (typeof START_PAGES)[number];
@@ -49,10 +48,10 @@ export interface UserPreferenceDto {
export type UserPreferencePatch = Partial<UserPreferenceDto>;
-export function defaults(): UserPreferenceDto {
+export function defaults(locale: Locale = DEFAULT_LOCALE): UserPreferenceDto {
return {
timezone: 'UTC',
- locale: 'en',
+ locale,
theme: 'system',
issueOpenMode: 'panel',
startPage: 'work-items',
@@ -108,7 +107,10 @@ function toDto(row: {
}
// A user's preferences, or the defaults when they have no row yet.
-export async function getPreferences(userId: string): Promise<UserPreferenceDto> {
+export async function getPreferences(
+ userId: string,
+ defaultLocale: Locale = DEFAULT_LOCALE,
+): Promise<UserPreferenceDto> {
const rows = await db
.select({
timezone: userPreference.timezone,
@@ -126,7 +128,7 @@ export async function getPreferences(userId: string): Promise<UserPreferenceDto>
})
.from(userPreference)
.where(eq(userPreference.userId, userId));
- return rows[0] ? toDto(rows[0]) : defaults();
+ return rows[0] ? toDto(rows[0]) : defaults(defaultLocale);
}
// Applies a partial update and returns the full result. Fields left out keep their
@@ -134,8 +136,9 @@ export async function getPreferences(userId: string): Promise<UserPreferenceDto>
export async function updatePreferences(
userId: string,
patch: UserPreferencePatch,
+ defaultLocale: Locale = DEFAULT_LOCALE,
): Promise<UserPreferenceDto> {
- const next = { ...(await getPreferences(userId)), ...patch };
+ const next = { ...(await getPreferences(userId, defaultLocale)), ...patch };
await db
.insert(userPreference)
.values({ userId, ...next })
diff --git a/apps/api/src/planner.ts b/apps/api/src/planner.ts
index 6f06b6d9..efe7582f 100644
--- a/apps/api/src/planner.ts
+++ b/apps/api/src/planner.ts
@@ -32,7 +32,7 @@ import { agentScheduleRoutes } from './modules/agents/schedules';
import { notificationRoutes } from './notifications/routes';
import { notificationSettingsRoutes } from './notification-settings/routes';
import { notificationPreferenceRoutes } from './notification-preferences/routes';
-import { userPreferenceRoutes } from './user-preferences/routes';
+import { userPreferenceRoutes } from './modules/user-preferences';
import { telegramRoutes } from './telegram/routes';
import { syncRoutes } from './sync/routes';
diff --git a/apps/api/src/user-preferences/routes.ts b/apps/api/src/user-preferences/routes.ts
deleted file mode 100644
index 30999ea4..00000000
--- a/apps/api/src/user-preferences/routes.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { Elysia, t } from 'elysia';
-import { authContext } from '../shared/auth-context';
-import { requireUser } from '../shared/access';
-import { getMembership } from '../members/store';
-import { HttpError } from '../shared/lib';
-import { errors } from '../shared/responses';
-import { HotkeyCombosSchema } from '../settings/hotkeys';
-import { getPreferences, isValidTimezone, updatePreferences } from './store';
-
-const Locale = t.Union([t.Literal('en'), t.Literal('uk'), t.Literal('ru'), t.Literal('zh-CN')]);
-const Theme = t.Union([t.Literal('light'), t.Literal('dark'), t.Literal('system')]);
-const IssueOpenMode = t.Union([t.Literal('panel'), t.Literal('page')]);
-const StartPage = t.Union([
- t.Literal('inbox'),
- t.Literal('dashboard'),
- t.Literal('work-items'),
- t.Literal('initiatives'),
- t.Literal('ai-chat'),
-]);
-
-const IssueStatsView = t.Union([t.Literal('compact'), t.Literal('timeline')]);
-const IssueActivityView = t.Union([t.Literal('flat'), t.Literal('grouped')]);
-
-const PreferenceResponse = t.Object({
- timezone: t.String(),
- locale: Locale,
- theme: Theme,
- issueOpenMode: IssueOpenMode,
- startPage: StartPage,
- showChatByDefault: t.Boolean(),
- issueStatsOpen: t.Boolean(),
- issueStatsView: IssueStatsView,
- issueActivityView: IssueActivityView,
- autoWatch: t.Boolean(),
- lastProjectId: t.Nullable(t.Number()),
- hotkeys: HotkeyCombosSchema,
-});
-
-const PreferencePatch = t.Object({
- timezone: t.Optional(t.String({ minLength: 1, maxLength: 64 })),
- locale: t.Optional(Locale),
- theme: t.Optional(Theme),
- issueOpenMode: t.Optional(IssueOpenMode),
- startPage: t.Optional(StartPage),
- showChatByDefault: t.Optional(t.Boolean()),
- issueStatsOpen: t.Optional(t.Boolean()),
- issueStatsView: t.Optional(IssueStatsView),
- issueActivityView: t.Optional(IssueActivityView),
- autoWatch: t.Optional(t.Boolean()),
- lastProjectId: t.Optional(t.Nullable(t.Number())),
- // The full set of the user's overrides: a shortcut left out falls back to the
- // instance binding.
- hotkeys: t.Optional(HotkeyCombosSchema),
-});
-
-// The session user's own interface preferences: timezone, language, theme, how a clicked issue
-// opens, which section the app root lands on, whether the floating AI chat starts
-// visible, how an issue's status stats section starts out, whether they are
-// subscribed to the issues they touch, and the project they were in last. Every
-// route is self-scoped to the session user, so no project guard applies — a user
-// only ever reads or writes their own row. Not MCP tools: an agent has no business
-// changing a person's UI settings.
-export const userPreferenceRoutes = new Elysia({
- name: 'user-preferences',
- detail: { tags: ['Settings'] },
-})
- .use(authContext)
-
- .get('/account/preferences', ({ user }) => getPreferences(requireUser(user).id), {
- response: { 200: PreferenceResponse, ...errors(401) },
- detail: {
- summary: 'Get account preferences',
- description:
- "Get the current user's interface preferences. Returns the defaults when none were saved.",
- },
- })
-
- .patch(
- '/account/preferences',
- async ({ user, body }) => {
- const current = requireUser(user);
- if (body.timezone !== undefined && !isValidTimezone(body.timezone)) {
- throw new HttpError(400, 'Unknown timezone');
- }
- // Only a project the user belongs to can be remembered, so the stored id can
- // never point at one they cannot open.
- if (body.lastProjectId != null && !(await getMembership(body.lastProjectId, current.id))) {
- throw new HttpError(403, 'You do not have access to this project');
- }
- return updatePreferences(current.id, body);
- },
- {
- body: PreferencePatch,
- response: { 200: PreferenceResponse, ...errors(400, 401, 403) },
- detail: {
- summary: 'Update account preferences',
- description:
- "Update the current user's interface preferences. Omitted fields keep their current value.",
- },
- },
- );
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index ef1a197c..00eb00ce 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -60,7 +60,7 @@ next-intl, language from the `NEXT_LOCALE` cookie — no `[locale]` route segmen
an untranslated one renders its English text.
- A new namespace needs its file in every language plus an entry in `defaultMessages`.
- A new language: `messages/<code>/`, `src/i18n/locales.ts`, `src/hooks/useDateFnsLocale.ts`,
- and `LOCALES`/`Locale` in `apps/api/src/user-preferences/`. No migration — the `locale`
+ and `LOCALES`/`Locale` in `apps/api/src/modules/user-preferences/`. No migration — the `locale`
column has no CHECK.
- Don't subset messages per route with `pick()`: a missing namespace then fails at runtime
instead of at typecheck.
diff --git a/apps/web/src/i18n/accept-language.test.ts b/apps/web/src/i18n/accept-language.test.ts
new file mode 100644
index 00000000..c7023c03
--- /dev/null
+++ b/apps/web/src/i18n/accept-language.test.ts
@@ -0,0 +1,21 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { localeFromAcceptLanguage } from './accept-language';
+
+describe('localeFromAcceptLanguage', () => {
+ it('uses the preferred supported language', () => {
+ assert.equal(localeFromAcceptLanguage('ru;q=0.4,zh-CN;q=0.9,en;q=0.8'), 'zh-CN');
+ });
+
+ it('matches a supported base language to a regional browser locale', () => {
+ assert.equal(localeFromAcceptLanguage('uk-UA,uk;q=0.9,en;q=0.8'), 'uk');
+ });
+
+ it('uses the fallback for a preferred wildcard', () => {
+ assert.equal(localeFromAcceptLanguage('de-DE,*;q=0.9,zh;q=0.8'), 'en');
+ });
+
+ it('falls back to English when no requested language is supported', () => {
+ assert.equal(localeFromAcceptLanguage('de-DE,fr;q=0.9'), 'en');
+ });
+});
diff --git a/apps/web/src/i18n/accept-language.ts b/apps/web/src/i18n/accept-language.ts
new file mode 100644
index 00000000..50cb1e2e
--- /dev/null
+++ b/apps/web/src/i18n/accept-language.ts
@@ -0,0 +1,32 @@
+import { DEFAULT_LOCALE, LOCALES, type Locale } from './locales';
+
+// Keep this matcher aligned with the API copy so the first server render and
+// an account without saved preferences resolve to the same language.
+export function localeFromAcceptLanguage(value: string | null): Locale {
+ const requested = (value ?? '')
+ .split(',')
+ .map((part, index) => {
+ const [tag, ...parameters] = part.trim().split(';');
+ const qualityValue = parameters
+ .map((parameter) => parameter.trim().toLowerCase())
+ .find((parameter) => parameter.startsWith('q='))
+ ?.slice(2);
+ const quality = qualityValue === undefined ? 1 : Number(qualityValue);
+ return { tag: tag.toLowerCase(), quality, index };
+ })
+ .filter(({ tag, quality }) => tag && quality > 0 && quality <= 1)
+ .sort((a, b) => b.quality - a.quality || a.index - b.index);
+
+ for (const { tag } of requested) {
+ if (tag === '*') return DEFAULT_LOCALE;
+
+ const exact = LOCALES.find((locale) => locale.toLowerCase() === tag);
+ if (exact) return exact;
+
+ const language = tag.split('-')[0];
+ const sameLanguage = LOCALES.find((locale) => locale.toLowerCase().split('-')[0] === language);
+ if (sameLanguage) return sameLanguage;
+ }
+
+ return DEFAULT_LOCALE;
+}
diff --git a/apps/web/src/i18n/request.ts b/apps/web/src/i18n/request.ts
index 14fc72fc..9cde67ac 100644
--- a/apps/web/src/i18n/request.ts
+++ b/apps/web/src/i18n/request.ts
@@ -1,14 +1,17 @@
-import { cookies } from 'next/headers';
+import { cookies, headers } from 'next/headers';
import { getRequestConfig } from 'next-intl/server';
-import { DEFAULT_LOCALE, LOCALE_COOKIE, isLocale } from './locales';
+import { localeFromAcceptLanguage } from './accept-language';
+import { LOCALE_COOKIE, isLocale } from './locales';
import { loadMessages } from './messages';
-// The app has no `[locale]` route segment: the language comes from a cookie, so every
-// URL stays the same in every language. The account preference is the durable copy
-// and the switcher writes both.
+// The app has no `[locale]` route segment, so every URL stays the same in every
+// language. The account preference is the durable copy, the cookie selects later
+// server renders, and the browser preference selects the first render without one.
export default getRequestConfig(async () => {
const cookie = (await cookies()).get(LOCALE_COOKIE)?.value;
- const locale = isLocale(cookie) ? cookie : DEFAULT_LOCALE;
+ const locale = isLocale(cookie)
+ ? cookie
+ : localeFromAcceptLanguage((await headers()).get('accept-language'));
return {
locale,
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index ddfa4273..4b4ac5e3 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -2894,10 +2894,14 @@ export const api = {
// The session user's own interface preferences, held per account. A read returns
// the defaults when nothing was saved; a write patches only the fields it carries.
- getAccountPreferences: () => request<AccountPreferences>('/account/preferences'),
- updateAccountPreferences: (input: AccountPreferencesPatch) =>
+ getAccountPreferences: (locale: Locale) =>
+ request<AccountPreferences>('/account/preferences', {
+ headers: { 'Accept-Language': locale },
+ }),
+ updateAccountPreferences: (input: AccountPreferencesPatch, locale: Locale) =>
request<AccountPreferences>('/account/preferences', {
method: 'PATCH',
+ headers: { 'Accept-Language': locale },
body: JSON.stringify(input),
}),
diff --git a/apps/web/src/services/preferences.service.ts b/apps/web/src/services/preferences.service.ts
index 8e3ace0b..0e68963d 100644
--- a/apps/web/src/services/preferences.service.ts
+++ b/apps/web/src/services/preferences.service.ts
@@ -1,4 +1,6 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { useLocale } from 'next-intl';
+import type { Locale } from '@/i18n/locales';
import { api, type AccountPreferences, type AccountPreferencesPatch } from '@/lib/api';
import { useSession } from '@/lib/auth-client';
import { qk } from '@/services/queryKeys';
@@ -25,9 +27,10 @@ export const PREFERENCE_DEFAULTS: AccountPreferences = {
export function useAccountPreferencesQuery() {
const { data: session } = useSession();
+ const locale = useLocale() as Locale;
return useQuery({
queryKey: qk.accountPreferences,
- queryFn: () => api.getAccountPreferences(),
+ queryFn: () => api.getAccountPreferences(locale),
// The route needs a session; the login and invite screens have none.
enabled: Boolean(session),
// Rarely change and are read on every screen, so keep them out of the refetch path.
@@ -43,8 +46,9 @@ export function useAccountPreferences(): AccountPreferences {
export function useUpdateAccountPreferences() {
const qc = useQueryClient();
+ const locale = useLocale() as Locale;
return useMutation({
- mutationFn: (input: AccountPreferencesPatch) => api.updateAccountPreferences(input),
+ mutationFn: (input: AccountPreferencesPatch) => api.updateAccountPreferences(input, locale),
// Merge into the cache before the request completes: a second change made while
// the first is still in flight is then built on the new value, not the stored
// one, and the app (theme, timezone) reacts immediately.
diff --git a/docs/dev/i18n.md b/docs/dev/i18n.md
index cddda110..b92b75b4 100644
--- a/docs/dev/i18n.md
+++ b/docs/dev/i18n.md
@@ -1,7 +1,9 @@
# Languages
-The interface language is an account preference. A cookie gives it to the server render, and
-next-intl reads that cookie one time for each request.
+The account preference is the durable interface language. The server render reads its local copy
+from a cookie one time for each request. Without that cookie, it uses the first supported language
+in the browser's `Accept-Language` header. English is the fallback when the header contains no
+supported language. After sign-in, the account preference replaces a different rendered language.
## The message files
@@ -25,13 +27,14 @@ namespace at a time.
| `apps/web/messages/<locale>/*.json` | the messages, one file for each namespace |
| `apps/web/src/i18n/messages.ts` | the English imports, `loadMessages`, the English fallback |
| `apps/web/src/i18n/request.ts` | reads the cookie and gives the messages to next-intl |
+| `apps/web/src/i18n/accept-language.ts` | matches the browser language to a supported language |
| `apps/web/src/i18n/locales.ts` | the language list, the labels, the flags, `isLocale` |
| `apps/web/src/i18n/cookie.ts` | writes `NEXT_LOCALE` |
| `apps/web/global.d.ts` | types each key against the English files |
| `apps/web/src/components/preferences-sync.tsx` | writes the cookie from the account preference, and refreshes |
| `apps/web/src/components/locale-toggle.tsx` | the language switcher |
| `apps/web/src/hooks/useDateFnsLocale.ts` | the month names and the weekday names of the calendar |
-| `apps/api/src/user-preferences/` | the stored preference and its validation |
+| `apps/api/src/modules/user-preferences/` | the stored preference and its validation |
## How to add a key
@@ -56,8 +59,8 @@ There are four locations, and no migration is necessary.
3. Add the applicable import from `date-fns/locale` to
`apps/web/src/hooks/useDateFnsLocale.ts`. If you do not, the month names and the weekday
names of the calendar stay in English, and no error occurs.
-4. Add the code to `LOCALES` in `apps/api/src/user-preferences/store.ts`, and to `Locale` in
- `routes.ts`. If you do not, the API refuses the new code with status 422, and the switcher
+4. Add the code to `LOCALES` in `apps/api/src/modules/user-preferences/locale.ts`, and to `Locale`
+ in `model.ts`. If you do not, the API refuses the new code with status 422, and the switcher
cannot save it.
The `user_preference.locale` column is a plain `text` column with no CHECK, so the set of