Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Add cookie-based localization infrastructure (#2506)

Luke Vella9da362afe11c
diff --git a/apps/web/src/features/user/actions.ts b/apps/web/src/features/user/actions.ts
index d465d7f91..30e524675 100644
--- a/apps/web/src/features/user/actions.ts
+++ b/apps/web/src/features/user/actions.ts
@@ -2,8 +2,13 @@
import { subject } from "@casl/ability";
import { prisma } from "@rallly/database";
import * as z from "zod";
-import { updateUserImage, updateUserName } from "@/features/user/mutations";
+import {
+ updateUserImage,
+ updateUserLocalization,
+ updateUserName,
+} from "@/features/user/mutations";
import { AppError } from "@/lib/errors";
+import { timeFormatSchema, weekStartSchema } from "@/lib/localization/schema";
import {
adminActionClient,
authActionClient,
@@ -13,6 +18,7 @@ import {
deleteImageFromS3,
getImageUploadUrl,
} from "@/lib/storage/image-upload";
+import { timezoneSchema } from "@/utils/timezone-schema";
export const updateUserNameAction = authActionClient
.metadata({ actionName: "update_user_name" })
@@ -25,6 +31,24 @@ export const updateUserNameAction = authActionClient
await updateUserName({ userId: ctx.user.id, name: parsedInput.name });
});
+export const updateLocalizationAction = authActionClient
+ .metadata({ actionName: "update_localization" })
+ .inputSchema(
+ z.object({
+ timeZone: timezoneSchema.optional(),
+ timeFormat: timeFormatSchema.optional(),
+ weekStart: weekStartSchema.optional(),
+ }),
+ )
+ .action(async ({ ctx, parsedInput }) => {
+ await updateUserLocalization({
+ userId: ctx.user.id,
+ timeZone: parsedInput.timeZone,
+ timeFormat: parsedInput.timeFormat,
+ weekStart: parsedInput.weekStart,
+ });
+ });
+
export const getAvatarUploadUrlAction = authActionClient
.metadata({ actionName: "get_avatar_upload_url" })
.use(createRateLimitMiddleware(10, "1 h"))
diff --git a/apps/web/src/features/user/mutations.ts b/apps/web/src/features/user/mutations.ts
index 7595c132b..fd905124b 100644
--- a/apps/web/src/features/user/mutations.ts
+++ b/apps/web/src/features/user/mutations.ts
@@ -77,6 +77,30 @@ export async function updateUserImage({
revalidateTag(userProfileTag(userId), "max");
}
+// Localization is written directly via Prisma (not Better-Auth): the cookie is
+// the SSR source of truth, so the session cache doesn't need refreshing here.
+// Undefined fields are no-ops in Prisma, giving patch semantics.
+export async function updateUserLocalization({
+ userId,
+ timeZone,
+ timeFormat,
+ weekStart,
+}: {
+ userId: string;
+ timeZone?: string;
+ timeFormat?: TimeFormat;
+ weekStart?: number;
+}) {
+ await prisma.user.update({
+ where: { id: userId },
+ data: {
+ timeZone,
+ timeFormat,
+ weekStart,
+ },
+ });
+}
+
export async function setActiveSpace({
userId,
spaceId,
diff --git a/apps/web/src/lib/localization/boundary.tsx b/apps/web/src/lib/localization/boundary.tsx
new file mode 100644
index 000000000..3af2718d2
--- /dev/null
+++ b/apps/web/src/lib/localization/boundary.tsx
@@ -0,0 +1,15 @@
+import type React from "react";
+import { LocalizationProvider } from "@/lib/localization/context";
+import { getLocalization } from "@/lib/localization/server";
+
+export async function LocalizationBoundary({
+ children,
+}: {
+ children?: React.ReactNode;
+}) {
+ const initial = await getLocalization();
+
+ return (
+ <LocalizationProvider initial={initial}>{children}</LocalizationProvider>
+ );
+}
diff --git a/apps/web/src/lib/localization/constants.ts b/apps/web/src/lib/localization/constants.ts
new file mode 100644
index 000000000..c95354d7d
--- /dev/null
+++ b/apps/web/src/lib/localization/constants.ts
@@ -0,0 +1,6 @@
+// Locale reuses the existing `rallly_locale` cookie (see `@/lib/locale/constants`).
+// Each preference gets its own cookie so the async timezone detector can't
+// read-merge-write-clobber a concurrent change to a different preference.
+export const TIMEZONE_COOKIE = "rallly_timezone";
+export const TIME_FORMAT_COOKIE = "rallly_time_format";
+export const WEEK_START_COOKIE = "rallly_week_start";
diff --git a/apps/web/src/lib/localization/context.tsx b/apps/web/src/lib/localization/context.tsx
new file mode 100644
index 000000000..de7aa1abb
--- /dev/null
+++ b/apps/web/src/lib/localization/context.tsx
@@ -0,0 +1,70 @@
+"use client";
+
+import type { TimeFormat } from "@rallly/database";
+import React from "react";
+import { useRequiredContext } from "@/components/use-required-context";
+import {
+ setTimeFormatCookie,
+ setTimeZoneCookie,
+ setWeekStartCookie,
+} from "@/lib/localization/cookies";
+import type { Localization } from "@/lib/localization/schema";
+
+type LocalizationContextValue = Localization & {
+ setTimeZone: (timeZone: string) => void;
+ setTimeFormat: (timeFormat: TimeFormat) => void;
+ setWeekStart: (weekStart: number) => void;
+};
+
+const LocalizationContext =
+ React.createContext<LocalizationContextValue | null>(null);
+
+LocalizationContext.displayName = "LocalizationContext";
+
+export function LocalizationProvider({
+ children,
+ initial,
+}: {
+ children?: React.ReactNode;
+ initial: Localization;
+}) {
+ const [state, setState] = React.useState(initial);
+
+ // Each setter updates local state instantly, then persists to the cookie
+ // (next-request SSR / cross-device read). No DB write — that happens only on
+ // an explicit save in the "Language & Region" settings — and no router.refresh.
+ const setTimeZone = React.useCallback((timeZone: string) => {
+ setState((prev) => ({ ...prev, timeZone }));
+ setTimeZoneCookie(timeZone);
+ }, []);
+
+ const setTimeFormat = React.useCallback((timeFormat: TimeFormat) => {
+ setState((prev) => ({ ...prev, timeFormat }));
+ setTimeFormatCookie(timeFormat);
+ }, []);
+
+ const setWeekStart = React.useCallback((weekStart: number) => {
+ setState((prev) => ({ ...prev, weekStart }));
+ setWeekStartCookie(weekStart);
+ }, []);
+
+ const value = React.useMemo(
+ () => ({ ...state, setTimeZone, setTimeFormat, setWeekStart }),
+ [state, setTimeZone, setTimeFormat, setWeekStart],
+ );
+
+ return (
+ <LocalizationContext.Provider value={value}>
+ {children}
+ </LocalizationContext.Provider>
+ );
+}
+
+export function useLocalization() {
+ return useRequiredContext(LocalizationContext);
+}
+
+// Timezone is its own concern → thin selector.
+export function useTimeZone() {
+ return useLocalization().timeZone;
+}
diff --git a/apps/web/src/lib/localization/cookies.ts b/apps/web/src/lib/localization/cookies.ts
new file mode 100644
index 000000000..3594d72a0
--- /dev/null
+++ b/apps/web/src/lib/localization/cookies.ts
@@ -0,0 +1,27 @@
+"use client";
+
+import type { TimeFormat } from "@rallly/database";
+import Cookies from "js-cookie";
+import {
+ TIME_FORMAT_COOKIE,
+ TIMEZONE_COOKIE,
+ WEEK_START_COOKIE,
+} from "@/lib/localization/constants";
+
+const cookieOptions = {
+ path: "/",
+ domain: process.env.NEXT_PUBLIC_COOKIE_DOMAIN,
+ expires: 400,
+};
+
+export function setTimeZoneCookie(timeZone: string) {
+ Cookies.set(TIMEZONE_COOKIE, timeZone, cookieOptions);
+}
+
+export function setTimeFormatCookie(timeFormat: TimeFormat) {
+ Cookies.set(TIME_FORMAT_COOKIE, timeFormat, cookieOptions);
+}
+
+export function setWeekStartCookie(weekStart: number) {
+ Cookies.set(WEEK_START_COOKIE, String(weekStart), cookieOptions);
+}
diff --git a/apps/web/src/lib/localization/locale-defaults.ts b/apps/web/src/lib/localization/locale-defaults.ts
new file mode 100644
index 000000000..6df403b58
--- /dev/null
+++ b/apps/web/src/lib/localization/locale-defaults.ts
@@ -0,0 +1,34 @@
+import type { TimeFormat } from "@rallly/database";
+import type { SupportedLocale } from "@rallly/languages";
+
+type LocaleDefaults = {
+ weekStart: number;
+ timeFormat: TimeFormat;
+};
+
+// Default time format / week start per locale. Server-safe (no dayjs imports)
+// so `getLocalization()` can resolve fallbacks.
+const localeDefaults: Record<SupportedLocale, LocaleDefaults> = {
+ en: { weekStart: 1, timeFormat: "hours12" },
+ "en-GB": { weekStart: 1, timeFormat: "hours24" },
+ es: { weekStart: 1, timeFormat: "hours24" },
+ da: { weekStart: 1, timeFormat: "hours24" },
+ de: { weekStart: 1, timeFormat: "hours24" },
+ fi: { weekStart: 1, timeFormat: "hours24" },
+ fr: { weekStart: 1, timeFormat: "hours24" },
+ it: { weekStart: 1, timeFormat: "hours24" },
+ sv: { weekStart: 1, timeFormat: "hours24" },
+ cs: { weekStart: 1, timeFormat: "hours24" },
+ pl: { weekStart: 1, timeFormat: "hours24" },
+ pt: { weekStart: 1, timeFormat: "hours24" },
+ "pt-BR": { weekStart: 0, timeFormat: "hours24" },
+ ru: { weekStart: 1, timeFormat: "hours24" },
+ nl: { weekStart: 1, timeFormat: "hours24" },
+ no: { weekStart: 1, timeFormat: "hours24" },
+ hu: { weekStart: 1, timeFormat: "hours24" },
+ zh: { weekStart: 1, timeFormat: "hours24" },
+};
+
+export function getLocaleDefaults(locale: string): LocaleDefaults {
+ return localeDefaults[locale as SupportedLocale] ?? localeDefaults.en;
+}
diff --git a/apps/web/src/lib/localization/schema.ts b/apps/web/src/lib/localization/schema.ts
new file mode 100644
index 000000000..4bf394dff
--- /dev/null
+++ b/apps/web/src/lib/localization/schema.ts
@@ -0,0 +1,14 @@
+import type { TimeFormat } from "@rallly/database";
+import * as z from "zod";
+
+export const timeFormatSchema = z.enum(["hours12", "hours24"]);
+
+// Coerces a cookie string ("0".."6") into a numeric weekday index.
+export const weekStartSchema = z.coerce.number().int().min(0).max(6);
+
+export type Localization = {
+ locale: string;
+ timeZone?: string;
+ timeFormat: TimeFormat;
+ weekStart: number;
+};
diff --git a/apps/web/src/lib/localization/server.test.ts b/apps/web/src/lib/localization/server.test.ts
new file mode 100644
index 000000000..cc4998430
--- /dev/null
+++ b/apps/web/src/lib/localization/server.test.ts
@@ -0,0 +1,125 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+// Make `cache()` a pass-through so each call re-runs (no request-scoped memo).
+vi.mock("react", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react")>();
+ return { ...actual, cache: (fn: unknown) => fn };
+});
+
+const cookieStore = new Map<string, string>();
+const mockGetLocale = vi.fn<() => Promise<string>>();
+const mockGetCurrentUser = vi.fn();
+
+vi.mock("next/headers", () => ({
+ cookies: async () => ({
+ get: (name: string) =>
+ cookieStore.has(name) ? { value: cookieStore.get(name) } : undefined,
+ }),
+}));
+
+vi.mock("@/i18n/server/get-locale", () => ({
+ getLocale: () => mockGetLocale(),
+}));
+
+vi.mock("@/auth/data", () => ({
+ getCurrentUser: () => mockGetCurrentUser(),
+}));
+
+import {
+ TIME_FORMAT_COOKIE,
+ TIMEZONE_COOKIE,
+ WEEK_START_COOKIE,
+} from "@/lib/localization/constants";
+import { getLocalization } from "@/lib/localization/server";
+
+beforeEach(() => {
+ cookieStore.clear();
+ mockGetLocale.mockReset().mockResolvedValue("en");
+ mockGetCurrentUser.mockReset().mockResolvedValue(null);
+});
+
+describe("getLocalization", () => {
+ it("uses cookie values and skips the DB when all cookies are present", async () => {
+ cookieStore.set(TIMEZONE_COOKIE, "America/New_York");
+ cookieStore.set(TIME_FORMAT_COOKIE, "hours24");
+ cookieStore.set(WEEK_START_COOKIE, "3");
+
+ const localization = await getLocalization();
+
+ expect(localization).toEqual({
+ locale: "en",
+ timeZone: "America/New_York",
+ timeFormat: "hours24",
+ weekStart: 3,
+ });
+ expect(mockGetCurrentUser).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the logged-in user's DB values when cookies are absent", async () => {
+ mockGetCurrentUser.mockResolvedValue({
+ timeZone: "Europe/Paris",
+ timeFormat: "hours24",
+ weekStart: 0,
+ });
+
+ const localization = await getLocalization();
+
+ expect(localization).toEqual({
+ locale: "en",
+ timeZone: "Europe/Paris",
+ timeFormat: "hours24",
+ weekStart: 0,
+ });
+ });
+
+ it("falls back to locale defaults for guests/anonymous (timeZone undefined)", async () => {
+ mockGetCurrentUser.mockResolvedValue(null);
+
+ const localization = await getLocalization();
+
+ // `en` defaults: weekStart 1, timeFormat hours12.
+ expect(localization).toEqual({
+ locale: "en",
+ timeZone: undefined,
+ timeFormat: "hours12",
+ weekStart: 1,
+ });
+ });
+
+ it("hits the DB when only some cookies are present", async () => {
+ cookieStore.set(TIMEZONE_COOKIE, "America/New_York");
+ mockGetCurrentUser.mockResolvedValue({
+ timeZone: "Europe/Paris",
+ timeFormat: "hours24",
+ weekStart: 0,
+ });
+
+ const localization = await getLocalization();
+
+ // timeZone comes from the cookie; the rest from the DB.
+ expect(localization).toEqual({
+ locale: "en",
+ timeZone: "America/New_York",
+ timeFormat: "hours24",
+ weekStart: 0,
+ });
+ expect(mockGetCurrentUser).toHaveBeenCalledTimes(1);
+ });
+
+ it("ignores invalid cookie values and falls back", async () => {
+ cookieStore.set(TIMEZONE_COOKIE, "America/New_York");
+ cookieStore.set(TIME_FORMAT_COOKIE, "bogus");
+ cookieStore.set(WEEK_START_COOKIE, "99");
+
+ const localization = await getLocalization();
+
+ expect(localization).toEqual({
+ locale: "en",
+ timeZone: "America/New_York",
+ timeFormat: "hours12",
+ weekStart: 1,
+ });
+ });
+});
diff --git a/apps/web/src/lib/localization/server.ts b/apps/web/src/lib/localization/server.ts
new file mode 100644
index 000000000..093107706
--- /dev/null
+++ b/apps/web/src/lib/localization/server.ts
@@ -0,0 +1,54 @@
+import "server-only";
+
+import { cookies } from "next/headers";
+import { cache } from "react";
+import { getCurrentUser } from "@/auth/data";
+import { getLocale } from "@/i18n/server/get-locale";
+import {
+ TIME_FORMAT_COOKIE,
+ TIMEZONE_COOKIE,
+ WEEK_START_COOKIE,
+} from "@/lib/localization/constants";
+import { getLocaleDefaults } from "@/lib/localization/locale-defaults";
+import type { Localization } from "@/lib/localization/schema";
+import { timeFormatSchema, weekStartSchema } from "@/lib/localization/schema";
+
+/**
+ * Resolves the viewer's localization for SSR.
+ *
+ * Each value falls back cookie → DB → locale default. The DB lookup is
+ * short-circuited: `getCurrentUser()` only runs when a cookie is missing, so
+ * anonymous/cookie-present viewers cost zero DB reads. `timeZone` has no locale
+ * default and stays undefined for guests/anonymous viewers (resolved client-side).
+ */
+export const getLocalization = cache(async (): Promise<Localization> => {
+ const [cookieStore, locale] = await Promise.all([cookies(), getLocale()]);
+
+ const timeZoneCookie = cookieStore.get(TIMEZONE_COOKIE)?.value;
+ const timeFormatCookie = timeFormatSchema.safeParse(
+ cookieStore.get(TIME_FORMAT_COOKIE)?.value,
+ );
+ const weekStartCookie = weekStartSchema.safeParse(
+ cookieStore.get(WEEK_START_COOKIE)?.value,
+ );
+
+ const needsDbFallback =
+ !timeZoneCookie || !timeFormatCookie.success || !weekStartCookie.success;
+
+ const user = needsDbFallback ? await getCurrentUser() : null;
+
+ const defaults = getLocaleDefaults(locale);
+
+ return {
+ locale,
+ timeZone: timeZoneCookie ?? user?.timeZone ?? undefined,
+ timeFormat:
+ (timeFormatCookie.success ? timeFormatCookie.data : undefined) ??
+ user?.timeFormat ??
+ defaults.timeFormat,
+ weekStart:
+ (weekStartCookie.success ? weekStartCookie.data : undefined) ??
+ user?.weekStart ??
+ defaults.weekStart,
+ };
+});
diff --git a/apps/web/src/test/empty-module.ts b/apps/web/src/test/empty-module.ts
new file mode 100644
index 000000000..8d96cf5c5
--- /dev/null
+++ b/apps/web/src/test/empty-module.ts
@@ -0,0 +1,3 @@
+// Stub for `server-only` / `client-only` import guards under Vitest, which
+// don't ship as standalone packages outside the Next.js build.
+export {};
diff --git a/apps/web/vitest.config.mts b/apps/web/vitest.config.mts
index 9d2d907b8..b2f4ff38e 100644
--- a/apps/web/vitest.config.mts
+++ b/apps/web/vitest.config.mts
@@ -15,6 +15,8 @@ export default defineConfig({
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
+ "server-only": path.resolve(__dirname, "./src/test/empty-module.ts"),
+ "client-only": path.resolve(__dirname, "./src/test/empty-module.ts"),
},
},
});