Files
HealthLog/src/app/insights/page.tsx
T
Marc-André Bombeck e0387c5ceb perf(prefetch): server-prefetch above-the-fold data for /insights, /medications, /coach
Extend the dashboard's RSC server-prefetch pattern to three more route roots
so their above-the-fold content paints populated on first load instead of
flashing a shell that fills in on mount.

Each route gains a thin RSC wrapper that runs the same cached read its API
route uses, dehydrates the result under the exact client query key, and hands
it to the client leaf through a HydrationBoundary. Every wrapper fails soft to
today's client-fetch path on any error and honours the DASHBOARD_SSR_PREFETCH
kill-switch the e2e server sets.

- /insights: prefetch the dashboard snapshot — the same locale-keyed cell the
  dashboard warms, resolved once server-side so the key matches by
  construction. The AI briefing and the heavy analytics aggregations stay
  client-lazy (the briefing must never trigger generation; a cold analytics
  read would trade FCP for TTFB).
- /medications: prefetch the medications list through the shared
  caches.medications cell (extracted to src/lib/medications/list-read.ts). The
  list cell keeps refetchOnMount: "always" — a cross-device take/skip produces
  no client mutation event, so the mount refetch is a correctness gate; the
  prefetch removes the initial skeleton flash without dropping that guarantee.
- /coach: prefetch the nudge status (extracted to
  src/lib/ai/coach/nudge-status.ts) so the auto-open-most-recent decision is
  ready at hydrate, collapsing the one sequential waterfall. Only runs when the
  Coach surface is reachable; the streaming conversation is never warmed.

Add per-route tests pinning server-key === client-key, JSON wire-shape
round-trip, and the fail-soft / module-gate paths. Repoint the source-reading
insights, take-all-due, and Coach gate-cascade tests at the client leaves.
2026-07-18 20:36:19 +02:00

87 lines
4.0 KiB
TypeScript

import {
dehydrate,
HydrationBoundary,
QueryClient,
} from "@tanstack/react-query";
import { getSession } from "@/lib/auth/session";
import { readDashboardSnapshotCached } from "@/lib/dashboard/snapshot-read";
import { queryKeys } from "@/lib/query-keys";
import InsightsPageClient from "./page-client";
/**
* Thin RSC wrapper around the (client) Insights overview page.
*
* The Insights root fans out into ~6 mount queries after hydrate; the highest-
* value, cheapest, and safest to lift onto the server is the dashboard snapshot
* — the SAME `queryKeys.dashboardSnapshot(locale)` cell the dashboard warms
* (the hero's Tension Verdict + return-to-baseline ride it). Reading it through
* the shared `caches.analytics` SWR cell during SSR and handing it to TanStack
* via `HydrationBoundary` means an Insights visit no longer re-pays the snapshot
* round-trip on the client, and the hero's snapshot-derived band paints from the
* first HTML instead of after a client fetch.
*
* Contract notes (the v1.30.9 dashboard template):
* - THE CRUX — the snapshot cell is locale-keyed
* (`queryKeys.dashboardSnapshot(locale)`). The locale is resolved ONCE
* server-side by `readDashboardSnapshotCached` (via `resolveServerLocale`)
* and the client's `useDashboardSnapshot` keys on the SAME resolved locale
* from the i18n context — the identical mechanism the dashboard already
* relies on, so the server-seeded key equals the client key by construction.
* - The dehydrated VALUE is JSON-round-tripped so the hydrated shape is exactly
* what the client `queryFn` produces from the wire (ISO date strings), never
* a Date-carrying sibling that poisons the cell.
* - The client snapshot cell reads `refetchOnMount: false`, so the seeded
* fresh value lands and is used without an immediate refetch.
* - The `["user","dashboardWidgets"]` layout the snapshot carries is seeded too
* (mirroring the client `queryFn`'s own seed), removing the widgets stage
* from the chart-overlay-prefs waterfall exactly as on the dashboard.
* - Left CLIENT-LAZY on purpose: the AI daily briefing (`GET /api/insights/
* generate`) — prefetching it must never trigger provider generation
* (generation stays cron + explicit-button only), so it keeps its own lazy
* read; and the heavy thick-analytics / comprehensive aggregations, whose
* COLD SWR cell is a multi-query scan — prefetching them synchronously would
* trade FCP for TTFB. Both stay on the client cells that own them.
* - Fail-soft: no session or a builder hiccup renders the page exactly as
* before this wrapper existed — the client cells own the fetch.
*/
export default async function InsightsPage() {
// Global SSR-prefetch kill-switch shared with the dashboard wrapper. The e2e
// server sets `DASHBOARD_SSR_PREFETCH=false` so Playwright route mocks — which
// only see CLIENT fetches — keep governing what every prefetched page paints.
if (process.env.DASHBOARD_SSR_PREFETCH === "false") {
return <InsightsPageClient />;
}
let dehydratedState = null;
try {
const session = await getSession();
if (session) {
const { user } = session;
const { body, locale } = await readDashboardSnapshotCached(user);
// Match the client cell's wire shape exactly (JSON semantics, ISO date
// strings) — same-key-different-shape is silent cache poison.
const wireBody = JSON.parse(JSON.stringify(body)) as unknown as Record<
string,
unknown
>;
const queryClient = new QueryClient();
queryClient.setQueryData(queryKeys.dashboardSnapshot(locale), wireBody);
queryClient.setQueryData(queryKeys.dashboardWidgets(), wireBody.layout);
dehydratedState = dehydrate(queryClient);
}
} catch {
// Prefetch is an accelerator, never a gate — the client path stands.
}
if (dehydratedState === null) {
return <InsightsPageClient />;
}
return (
<HydrationBoundary state={dehydratedState}>
<InsightsPageClient />
</HydrationBoundary>
);
}