Files
HealthLog/e2e/dashboard-ssr-prefetch-hydration.spec.ts
T
Marc-André Bombeck 675c70eba8 Keep the dashboard the server streamed
`/` runs its reads server-side and hands them to TanStack through a
HydrationBoundary, so the first HTML already carries real tiles. React threw
that away on every cold load. The app shell hydrates first and its mount
answers `/api/auth/me`; the dashboard sits below `loading.tsx`, hydrates later,
and its first client render therefore read an account the server never had.
That disagreed with the streamed HTML, React reported #418 and re-rendered the
whole page. The prefetch paid for its queries and delivered none of its paint.

The account payload is now withheld from the hydration render wherever it is
only rendered. `useAccountOnceMounted()` answers null until the component has
mounted, which is what the server rendered, and hands the payload over on the
next render. The dashboard page, the caregiver card, the getting-started
checklist, the achievements tile and the unit labels read it that way. `useAuth`
itself still reads the cache, because the document vault redirects off
`user.modules` and a first render claiming "no account" bounces it to `/`.

Two tiles disagreed without any account involved. A query reports `isLoading`
true on the client's first render and false on the server, so both now gate on
whether the cell holds an answer.

Nothing in CI ran the shipped configuration: the suite's server turns the
prefetch off so route mocks keep governing the dashboard. A second server runs
it on, and one spec asserts that no hydration error is reported and that the
tile node the server streamed is still the node in the DOM once the page
settles.

Measured over nine cold loads with the CPU throttled 4x: seven bailouts before
and none after, median LCP 869 ms before and 145 ms after. FCP and the time to
the first tile in the DOM are unchanged, because the streamed paint was never
the problem. Keeping it was.
2026-08-06 17:28:48 +02:00

101 lines
4.0 KiB
TypeScript

import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
import { SSR_PREFETCH_BASE_URL } from "./setup/ssr-prefetch-server";
/**
* The dashboard survives hydration in the configuration that ships.
*
* `/` is an RSC wrapper that runs the dashboard's reads server-side and hands
* them to TanStack through a `HydrationBoundary` (`src/app/page.tsx`), so the
* first HTML already carries real tiles. It only does that when
* `DASHBOARD_SSR_PREFETCH` is not `"false"` — which is the default, and
* therefore what every self-hoster runs.
*
* The rest of the suite runs against a server with that flag OFF, because the
* dashboard specs drive their fixtures through `page.route` and a route mock
* only sees client fetches. So nothing here ever exercised the shipped path,
* and a React #418 hydration bailout sat on `/` for a signed-in account on
* every cold load: the app shell hydrates first and its queries answer before
* the streamed dashboard boundary hydrates, so the dashboard's first CLIENT
* render read an account payload (and an achievements payload, and its own
* in-flight tiles) the server never had. React threw the streamed tree away
* and rebuilt it — paying for the prefetch and delivering none of it.
*
* This spec talks to the second server (`SSR_PREFETCH_BASE_URL`, prefetch ON,
* no route mocks, the real seeded account) and asserts two things a mocked
* spec cannot:
*
* 1. the browser reports no hydration error at all;
* 2. the tile node the SERVER streamed is still the same DOM node once the
* page settles. A bailout re-creates it, so node identity is the honest
* witness that the server's work survived instead of being re-done. The
* probe only reads identity — writing a marker attribute onto server HTML
* would be a hydration mismatch of its own making.
*
* Runs on both viewport projects, because the defect reproduced on both.
*/
declare global {
interface Window {
__ssrTileWitness?: { seen: boolean; replaced: number };
}
}
test.describe("dashboard hydration with the SSR prefetch on", () => {
test.use({
storageState: STORAGE_STATE_PATH,
baseURL: SSR_PREFETCH_BASE_URL,
});
test("streams the dashboard and keeps it through hydration", async ({
page,
}) => {
const clientErrors: string[] = [];
page.on("pageerror", (error) => clientErrors.push(error.message));
page.on("console", (message) => {
if (message.type() === "error") clientErrors.push(message.text());
});
// `addInitScript` runs before any page script, so the poll is armed for
// the very first frame and latches the node React hydrated into.
await page.addInitScript(() => {
const witness = { seen: false, replaced: 0 };
window.__ssrTileWitness = witness;
let node: Element | null = null;
const poll = () => {
const el = document.querySelector('[data-slot="dashboard-tile-strip"]');
if (el) {
if (!node) witness.seen = true;
else if (node !== el) witness.replaced += 1;
node = el;
}
requestAnimationFrame(poll);
};
requestAnimationFrame(poll);
});
await page.goto("/");
const strip = page.locator('[data-slot="dashboard-tile-strip"]');
await expect(strip).toBeVisible();
// The seeded account owns one weight reading, so the strip carries a real
// tile — proof the prefetch populated this render rather than the client
// having filled it in after mount.
await expect(
strip.locator('[data-slot="dashboard-tile-link"]').first(),
).toBeVisible();
// Let every boundary hydrate and every post-mount refetch land before the
// verdict; a bailout that happens late is still a bailout.
await page.waitForLoadState("networkidle");
expect(
clientErrors.filter((message) => /418|hydrat/i.test(message)),
).toEqual([]);
const witness = await page.evaluate(() => window.__ssrTileWitness);
expect(witness?.seen).toBe(true);
expect(witness?.replaced).toBe(0);
});
});