A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!
TypeScript agent-skillsaidsh-pluginhacktoberfestjavascriptmcp-serverreactresume-builderself-hostedtypescript
fix: detect first-visit language without varying shared HTML
Amruth Pillai3759f3f92f90
diff --git a/apps/mobile/src/i18n/index.ts b/apps/mobile/src/i18n/index.tsindex 5c863f5d6..0efa0bda5 100644--- a/apps/mobile/src/i18n/index.ts+++ b/apps/mobile/src/i18n/index.ts@@ -6,7 +6,14 @@ import { i18n } from "@lingui/core";import { getLocales } from "expo-localization";import Storage from "expo-sqlite/kv-store";import { I18nManager, Platform, Settings } from "react-native";-import { defaultLocale, isLocale, isRTL, localeSchema, supportedLocales } from "@reactive-resume/utils/locale";+import {+ defaultLocale,+ getPreferredLocale,+ isLocale,+ isRTL,+ localeSchema,+ supportedLocales,+} from "@reactive-resume/utils/locale";const storageKey = "locale";export const selectableLocales = __DEV__ ? localeSchema.options : supportedLocales;@@ -72,13 +79,7 @@ const loaders: Record<Locale, () => Promise<{ messages: Messages }>> = {/** The supported locale closest to the device's preferred languages. */export function getDeviceLocale(): Locale {- const supported = supportedLocales;- for (const { languageTag, languageCode } of getLocales()) {- if (isLocale(languageTag) && supported.includes(languageTag)) return languageTag;- const sameLanguage = supported.find((locale) => locale.split("-")[0] === languageCode);- if (sameLanguage) return sameLanguage;- }- return defaultLocale;+ return getPreferredLocale(getLocales().map(({ languageTag }) => languageTag));}/** The user's override, or null to follow the device. */diff --git a/apps/server/src/static/locale.ts b/apps/server/src/static/locale.tsnew file mode 100644index 000000000..9aa22204f--- /dev/null+++ b/apps/server/src/static/locale.ts@@ -0,0 +1,12 @@+import { defaultLocale, isLocale, supportedLocales } from "@reactive-resume/utils/locale";++/** Explicit website preference only. Shared HTML must not vary by Accept-Language. */+export function getPageLocale(request: Request) {+ const requested = new URL(request.url).searchParams.get("locale");+ if (isLocale(requested))+ return { locale: supportedLocales.includes(requested) ? requested : defaultLocale, requested: true };+ const saved = request.headers.get("cookie")?.match(/(?:^|;\s*)locale=([^;]*)/)?.[1];+ if (saved !== undefined)+ return { locale: isLocale(saved) && supportedLocales.includes(saved) ? saved : defaultLocale, requested: false };+ return null;+}diff --git a/apps/server/src/static/resume-page.test.ts b/apps/server/src/static/resume-page.test.tsindex b0035381a..379c219c5 100644--- a/apps/server/src/static/resume-page.test.ts+++ b/apps/server/src/static/resume-page.test.ts@@ -133,19 +133,30 @@ it("still shows a shared resume whose owner's username looks like an app page",expect(response.status).toBe(200);});-it("gives a visitor at an address with no shared resume a way to the app's home, in their language", async () => {- const { loadPublicWebPage } = await import("@reactive-resume/api/features/resume/web-page");- vi.mocked(loadPublicWebPage).mockResolvedValue({ status: "unavailable" } as never);- const { serveResumePage } = await import("./resume-page");+it.each([+ ["", undefined, "de-DE", "de-DE"],+ ["", "fr-FR", "de-DE", "fr-FR"],+ ["?locale=ja-JP", "fr-FR", "de-DE", "ja-JP"],+ ["", "zu-ZA", "de-DE", "en-US"],+])(+ "keeps explicit language ahead of the header on unavailable pages: %s %s",+ async (search, saved, header, expected) => {+ const { loadPublicWebPage } = await import("@reactive-resume/api/features/resume/web-page");+ vi.mocked(loadPublicWebPage).mockResolvedValue({ status: "unavailable" } as never);+ const { serveResumePage } = await import("./resume-page");- const response = await serveResumePage(- new Request("https://resume.example/unshared-user", { headers: { "accept-language": "de-DE" } }),- { username: "unshared-user", primary: true },- "test",- );+ const response = await serveResumePage(+ new Request(`https://resume.example/unshared-user${search}`, {+ headers: { "accept-language": header, ...(saved ? { cookie: `theme=light; locale=${saved}` } : {}) },+ }),+ { username: "unshared-user", primary: true },+ "test",+ );- const html = await response.text();- expect(response.status).toBe(404);- expect(html).toMatch(/<a class="home" href="https:\/\/resume\.example\/">.*<\/a><\/main>/);- expect(html).toContain('lang="de-DE"');-});+ const html = await response.text();+ expect(response.status).toBe(404);+ expect(html).toMatch(/<a class="home" href="https:\/\/resume\.example\/">.*<\/a><\/main>/);+ expect(html).toContain(`lang="${expected}"`);+ expect(response.headers.get("Cache-Control")).toBe("private, no-store");+ },+);diff --git a/apps/server/src/static/resume-page.ts b/apps/server/src/static/resume-page.tsindex bb61dcb56..77b505402 100644--- a/apps/server/src/static/resume-page.ts+++ b/apps/server/src/static/resume-page.ts@@ -16,6 +16,7 @@ import {import { publicResumePath } from "@reactive-resume/resume/sharing";import { getResumeSocialMeta } from "@reactive-resume/resume/social-meta";import { mistypedAppPath } from "@reactive-resume/utils/app-paths";+import { getPageLocale } from "./locale";import { BASE_SECURITY_HEADERS, contentSecurityPolicy } from "./web";const origin = () => new URL(env.APP_URL).origin;@@ -77,7 +78,7 @@ type PageOptions = {/** Off, unknown or trashed resumes read the same, in the visitor's language. */function unavailableResponse(request: Request) {- const lang = localeFromAcceptLanguage(request.headers.get("accept-language"));+ const lang = getPageLocale(request)?.locale ?? localeFromAcceptLanguage(request.headers.get("accept-language"));return html(renderUnavailableDocument({ lang, messages: webPageMessages(lang), homeUrl: `${origin()}/` }), 404);}diff --git a/apps/server/src/static/web.test.ts b/apps/server/src/static/web.test.tsindex 8d6636e37..a95e78e86 100644--- a/apps/server/src/static/web.test.ts+++ b/apps/server/src/static/web.test.ts@@ -124,6 +124,20 @@ describe("web app fallback classification", () => {expect(await unknown.text()).toContain('<div id="app">en-US</div>');});+ it("keeps shared HTML and its cache validators independent of browser language hints", async () => {+ vi.mocked(fs.readFile).mockImplementation((path) =>+ Promise.resolve(`<html><head></head><body>${String(path)}</body></html>`),+ );+ const german = await handleWebApp(new Request("https://rxresu.me/", { headers: { "accept-language": "de-DE" } }));+ const french = await handleWebApp(new Request("https://rxresu.me/", { headers: { "accept-language": "fr-FR" } }));+ const body = await german.text();+ expect(body).toContain("home/en-US.html");+ expect(await french.text()).toBe(body);+ expect(german.headers.get("ETag")).toBe(french.headers.get("ETag"));+ expect(german.headers.get("Vary")).toBe("Cookie");+ expect(german.headers.get("Set-Cookie")).toBeNull();+ });+it.each(["/", "/index.html"])("preserves request parameters in language links before JavaScript on %s",async (path) => {diff --git a/apps/server/src/static/web.ts b/apps/server/src/static/web.tsindex a1ea12b4c..009d5e797 100644--- a/apps/server/src/static/web.ts+++ b/apps/server/src/static/web.ts@@ -8,14 +8,9 @@ import { env } from "@reactive-resume/env/server";import { jsonLdScript, socialMetaTags } from "@reactive-resume/pdf/web-page-document";import { templateSchema } from "@reactive-resume/schema/templates";import { isAppSectionPath, RESERVED_SEGMENTS } from "@reactive-resume/utils/app-paths";-import {- defaultLocale,- getLocaleAlternates,- isLocale,- localizedUrl,- supportedLocales,-} from "@reactive-resume/utils/locale";+import { defaultLocale, getLocaleAlternates, localizedUrl } from "@reactive-resume/utils/locale";import { escapeHtml } from "@reactive-resume/utils/string";+import { getPageLocale } from "./locale";import { CONTEXT7_ASK_DESCRIPTION, CONTEXT7_ASK_URL } from "./seo";function resolveWebDistPath() {@@ -326,19 +321,6 @@ function getFallbackResponseHeaders(pathname: string) {return null;}-/**- * A prerendered page's language: a `?locale=` address first (its hreflang alternates), then the visitor's saved- * choice, in the order the app reads them (apps/web/src/libs/locale.ts).- */-function getPageLocale(request: Request) {- const requested = new URL(request.url).searchParams.get("locale");- if (isLocale(requested))- return { locale: supportedLocales.includes(requested) ? requested : defaultLocale, requested: true };-- const saved = request.headers.get("cookie")?.match(/(?:^|;\s*)locale=([^;]*)/)?.[1] ?? "";- return { locale: isLocale(saved) && supportedLocales.includes(saved) ? saved : defaultLocale, requested: false };-}-/** Swaps the page's <title> and description. Function replacers keep `$&`, `$'` etc. in user text literal. */const withMeta = (html: string, meta: { title: string; description: string }) =>html@@ -415,7 +397,7 @@ export async function handleWebApp(request: Request, readFile: ReadWebFile = (paconst prerendered = prerenderedPages[pathname];if (prerendered) {- const { locale, requested } = getPageLocale(request);+ const { locale, requested } = getPageLocale(request) ?? { locale: defaultLocale, requested: false };const origin = new URL(env.APP_URL).origin;// Without a prerendered page (a build that skipped it), the app shell titled for the page renders it in the browser.const page = await readFile(`${prerenderRoot}/${prerendered.name}/${locale}.html`).catch(() =>diff --git a/apps/web/src/libs/locale.test.ts b/apps/web/src/libs/locale.test.tsindex 8311c8c96..7ec955773 100644--- a/apps/web/src/libs/locale.test.ts+++ b/apps/web/src/libs/locale.test.ts@@ -7,12 +7,41 @@ import { changeLocale, getLocale } from "./locale";beforeEach(() => {Cookies.remove("locale");+ window.history.replaceState(null, "", "/");+ vi.stubGlobal("navigator", { languages: ["en-US"] });vi.spyOn(window.location, "reload").mockImplementation(() => {});});afterEach(() => {Cookies.remove("locale");vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe("first-visit language", () => {+ it("follows the browser without persisting an inferred choice", () => {+ vi.stubGlobal("navigator", { languages: ["unsupported", "de-AT", "fr-FR"] });+ window.history.replaceState({ key: "visit" }, "", "/ats-checker?campaign=first#check");+ const href = window.location.href;+ expect(getLocale()).toBe("de-DE");+ expect(Cookies.get("locale")).toBeUndefined();+ expect(window.location.href).toBe(href);+ expect(window.history.state).toEqual({ key: "visit" });+ expect(window.location.reload).not.toHaveBeenCalled();+ });++ it.each([+ ["?locale=ja-JP", "fr-FR", "ja-JP"],+ ["?locale=en-US", undefined, "en-US"],+ ["", "fr-FR", "fr-FR"],+ ["?locale=unsupported", "fr-FR", "fr-FR"],+ ])("keeps explicit URL %s and cookie %s ahead of browser language", (search, saved, expected) => {+ vi.stubGlobal("navigator", { languages: ["de-DE"] });+ window.history.replaceState(null, "", `/${search}`);+ if (saved) Cookies.set("locale", saved);+ expect(getLocale()).toBe(expected);+ expect(Cookies.get("locale")).toBe(expected);+ });});describe("changeLocale", () => {diff --git a/apps/web/src/libs/locale.ts b/apps/web/src/libs/locale.tsindex ab0315f64..0bf0fae20 100644--- a/apps/web/src/libs/locale.ts+++ b/apps/web/src/libs/locale.ts@@ -3,7 +3,14 @@ import type { Locale } from "@reactive-resume/utils/locale";import { i18n } from "@lingui/core";import { msg } from "@lingui/core/macro";import Cookies from "js-cookie";-import { defaultLocale, isLocale, localeSchema, localizedUrl, supportedLocales } from "@reactive-resume/utils/locale";+import {+ defaultLocale,+ getPreferredLocale,+ isLocale,+ localeSchema,+ localizedUrl,+ supportedLocales,+} from "@reactive-resume/utils/locale";const storageKey = "locale";const persistLocale = (locale: Locale) => Cookies.set(storageKey, locale, { expires: 365, path: "/", sameSite: "lax" });@@ -115,8 +122,10 @@ export const getLocale = () => {return locale;}- const locale = Cookies.get(storageKey);- return resolveLocale(locale ?? defaultLocale);+ const saved = Cookies.get(storageKey);+ if (saved !== undefined) return resolveLocale(saved);+ // Browser hints affect the app only; neither persist them nor vary shared server HTML by Accept-Language.+ return getPreferredLocale(navigator.languages ?? []);};const loadMessages = async (locale: Locale) => {diff --git a/docs/guides/changing-appearance-and-language.mdx b/docs/guides/changing-appearance-and-language.mdxindex 62c2ad29e..feb42286b 100644--- a/docs/guides/changing-appearance-and-language.mdx+++ b/docs/guides/changing-appearance-and-language.mdx@@ -42,6 +42,10 @@ The change applies at once. Reactive Resume remembers it in this browser for a y## Change the interface language+On your first visit, the website follows your browser's preferred languages. It uses a supported regional variant when an exact match is unavailable, or English if none matches. This automatic choice isn't saved: a language in the page address (`?locale=`) or a choice already saved in this browser takes priority. Automatic selection needs JavaScript; homepage language links also work without it.++The Android and iPhone apps follow your device's preferred languages until you choose a language in Preferences.+<Steps><Step title="Open Preferences">Go to **Settings → Preferences**.diff --git a/packages/utils/src/locale.test.ts b/packages/utils/src/locale.test.tsindex 2bc8170a8..5d08a9512 100644--- a/packages/utils/src/locale.test.ts+++ b/packages/utils/src/locale.test.ts@@ -1,5 +1,29 @@import { describe, expect, it } from "vite-plus/test";-import { getLocaleAlternates, isLocale, localeSchema, localizedUrl, supportedLocales } from "./locale";+import {+ getLocaleAlternates,+ getPreferredLocale,+ isLocale,+ localeSchema,+ localizedUrl,+ supportedLocales,+} from "./locale";++it.each([+ [["de-DE"], "de-DE"],+ [["unsupported", "fr-CA", "de-DE"], "fr-FR"],+ [["de-AT", "fr-FR"], "de-DE"],+ [["de-de"], "de-DE"],+ [["de"], "de-DE"],+ [["en-GB", "en-US"], "en-GB"],+ [["pt-PT", "pt-BR"], "pt-PT"],+ [["zh-TW", "zh-CN"], "zh-TW"],+ [["zu-ZA", "de-DE"], "de-DE"],+ [["zu-ZA"], "en-US"],+ [["unsupported"], "en-US"],+ [[], "en-US"],+])("matches ordered language preferences %j to %s", (languages, expected) => {+ expect(getPreferredLocale(languages)).toBe(expected);+});it("keeps the testing catalog valid without counting it as a supported translation", () => {expect(isLocale("zu-ZA")).toBe(true);diff --git a/packages/utils/src/locale.ts b/packages/utils/src/locale.tsindex 822a25cf2..823604735 100644--- a/packages/utils/src/locale.ts+++ b/packages/utils/src/locale.ts@@ -84,6 +84,18 @@ const pseudoLocale: Locale = "zu-ZA";export const supportedLocales: readonly Locale[] = localeSchema.options.filter((locale) => locale !== pseudoLocale);+/** Follow ordered device/browser preferences without ever selecting the development pseudo-locale. */+export function getPreferredLocale(languages: readonly string[]): Locale {+ for (const language of languages) {+ const tag = language.toLowerCase();+ const exact = supportedLocales.find((locale) => locale.toLowerCase() === tag);+ if (exact) return exact;+ const sameLanguage = supportedLocales.find((locale) => locale.split("-")[0] === tag.split("-")[0]);+ if (sameLanguage) return sameLanguage;+ }+ return defaultLocale;+}+/** hreflang alternates for a page: every real locale plus x-default. "sr-SP" isn't a valid region, so it's "sr". */export function getLocaleAlternates(pageUrl: string) {const alternates = supportedLocales.map((locale) => ({diff --git a/tests/e2e/specs/first-visit-language.spec.ts b/tests/e2e/specs/first-visit-language.spec.tsnew file mode 100644index 000000000..46422c26a--- /dev/null+++ b/tests/e2e/specs/first-visit-language.spec.ts@@ -0,0 +1,48 @@+import { expect, test } from "../fixtures/test";++test.use({ locale: "de-AT" });++for (const path of ["/", "/ats-checker", "/auth/login"]) {+ test(`follows browser language on ${path} without saving an automatic choice`, async ({ page, context }) => {+ await page.goto(`${path}?campaign=first-visit`);+ await expect(page.locator("html")).toHaveAttribute("lang", "de-DE");+ if (path === "/auth/login") await expect(page.getByRole("button", { name: "Anmelden", exact: true })).toBeVisible();+ expect((await context.cookies()).find((cookie) => cookie.name === "locale")).toBeUndefined();+ expect(new URL(page.url()).searchParams.get("campaign")).toBe("first-visit");+ expect(new URL(page.url()).searchParams.has("locale")).toBe(false);+ await page.reload();+ await expect(page.locator("html")).toHaveAttribute("lang", "de-DE");+ expect((await context.cookies()).find((cookie) => cookie.name === "locale")).toBeUndefined();+ });+}++test("explicit language wins and the saved choice survives navigation", async ({ page, context, baseURL }) => {+ await context.addCookies([{ name: "locale", value: "fr-FR", url: baseURL ?? "http://localhost:3000" }]);+ await page.goto("/auth/login");+ await expect(page.locator("html")).toHaveAttribute("lang", "fr-FR");+ await page.goto("/?locale=ja-JP&campaign=explicit");+ await expect(page.locator("html")).toHaveAttribute("lang", "ja-JP");+ expect((await context.cookies()).find((cookie) => cookie.name === "locale")?.value).toBe("ja-JP");+ await page.goto("/auth/login");+ await expect(page.locator("html")).toHaveAttribute("lang", "ja-JP");+});++test("shared homepage HTML ignores Accept-Language while private unavailable pages honor explicit choice", async ({+ request,+}) => {+ const german = await request.get("/", { headers: { "accept-language": "de-DE" } });+ const french = await request.get("/", { headers: { "accept-language": "fr-FR" } });+ const germanHtml = await german.text();+ expect(germanHtml).toContain('lang="en-US"');+ expect(await french.text()).toBe(germanHtml);+ expect(german.headers().etag).toBe(french.headers().etag);+ expect(german.headers().vary).not.toMatch(/accept-language/i);+ expect(german.headers()["set-cookie"] ?? "").not.toContain("locale=");++ const unavailable = await request.get("/rx154-no-such-resume", {+ headers: { cookie: "locale=fr-FR", "accept-language": "de-DE" },+ });+ expect(unavailable.status()).toBe(404);+ expect(await unavailable.text()).toContain('lang="fr-FR"');+ expect(unavailable.headers()["cache-control"]).toBe("private, no-store");+});