diff --git a/.changeset/convexload-hydration-single-subscription.md b/.changeset/convexload-hydration-single-subscription.md new file mode 100644 index 0000000..388be1b --- /dev/null +++ b/.changeset/convexload-hydration-single-subscription.md @@ -0,0 +1,15 @@ +--- +'convex-svelte': minor +--- + +### Fixes + +- **With the new `convexLoadHydration` handle, `convexLoad` in `+page.ts` no longer queries without auth during hydration** - SvelteKit re-runs universal load functions in the browser during hydration, before `setupAuth()` has authenticated the client. `convexLoad` / `convexLoadPaginated` therefore queried Convex unauthenticated, replacing the server-rendered data with anonymous results (or failing the load for auth-protected queries). With the opt-in `convexLoadHydration` handle, the server embeds its results in the HTML and hydration reuses them: the live subscription starts after auth, and the page becomes interactive without waiting for the WebSocket. Without the handle, hydration still queries as before. +- **One subscription per `convexLoad`** - on client-side navigation, `convexLoad` ran a one-shot query and then subscribed again (Add → Remove → Add on the WebSocket), executing the query twice. It now opens the live subscription and awaits its first value. `convexLoadPaginated` no longer fetches the first page twice. + +- **No loading flash for paginated SSR data** - with SSR `initialData`, `convexLoadPaginated` (and `usePaginatedQuery` with `initialData`) briefly reported `isLoading: true` / `LoadingFirstPage` right after hydration, so pages rendered their loading state over the server-rendered results. The initial args and the subscription's first empty snapshot now keep the SSR results visible and not loading. + +### Features + +- **`convexLoadHydration`** - new SvelteKit `handle` exported from the new entry point `convex-svelte/sveltekit/server/hydration` (requires SvelteKit 2.56 or later). Add it to `hooks.server.ts` (combine with your own handle via `sequence()`) and put a `%convex.hydration%` placeholder in the `` of `src/app.html` to embed `convexLoad` results of universal loads in the SSR HTML. Without the placeholder nothing is embedded, and a dev warning says so. Everything `convexLoad` fetches while a universal load runs is embedded, including calls in helpers it invokes, but not inside remote functions. Server loads (`+page.server.ts`) never contribute, not even results they use internally, and the ones they return reach the browser through the transport. Universal loads and remote functions are detected via SvelteKit's internal `is_in_universal_load` and `is_in_remote_function` request-store flags (also used by SvelteKit's remote functions). If they can't be read, nothing is embedded and a warning is logged. Pages without results (e.g. `ssr = false`) get no payload and no dev warnings. An unreadable payload is ignored, so the load queries instead. It's a separate entry point so that `convex-svelte/sveltekit/server` keeps working on older SvelteKit versions. A streamed (not awaited) `convexLoad` result is only embedded if it finished before the page HTML was generated; in development, a warning points out loads that miss the payload during hydration. +- **`hydrate: false`** - `convexLoad` / `convexLoadPaginated` option to leave a result out of the SSR payload, e.g. a large one. That load then queries Convex during hydration, before `setupAuth()`, as it did without the handle. diff --git a/e2e/convexLoadHydration.test.ts b/e2e/convexLoadHydration.test.ts new file mode 100644 index 0000000..017c237 --- /dev/null +++ b/e2e/convexLoadHydration.test.ts @@ -0,0 +1,157 @@ +import { expect, test } from '@playwright/test'; +import { convexUrl, recordWebSocket, withMuteWord, type QueryEvent } from './helpers/websocket.js'; + +// --------------------------------------------------------------------------- +// convexLoad SSR hydration payload (convexLoadHydration handle in +// src/hooks.server.ts). +// +// SvelteKit re-runs universal loads (+page.ts) in the browser during +// hydration — before setupAuth() authenticated the client. They must reuse +// the server's results instead of querying unauthenticated, and open exactly +// one live subscription each. +// --------------------------------------------------------------------------- + +test.describe('convexLoad — SSR hydration payload', () => { + test('embeds results of universal loads in the HTML', async ({ page }) => { + const response = await page.goto('/tests/convex-load-release/a'); + const html = (await response?.text()) ?? ''; + + expect(html).toContain('data-convex-load'); + expect(html).toContain('__e2e_release_a__'); + // In , so it exists before SvelteKit's start script runs the loads. + expect(html.indexOf('data-convex-load')).toBeLessThan(html.indexOf('')); + }); + + test('never embeds server-load results (returned ones use the transport)', async ({ page }) => { + const websocket = recordWebSocket(page); + const response = await page.goto('/tests/convex-load-server'); + const html = (await response?.text()) ?? ''; + + // Nothing to embed: no payload element and no leftover placeholder… + expect(html).not.toContain('data-convex-load'); + expect(html).not.toContain('%convex.hydration%'); + // …and a result the server load only used internally never appears. + expect(html).not.toContain('__e2e_server_private__'); + // Still rendered from SSR and upgraded to a live subscription. + await expect(page.getByTestId('data')).toBeVisible(); + await expect(page.getByTestId('hydrated')).toContainText('true'); + await expect + .poll(() => websocket.queryEvents(withMuteWord('__e2e_server_load__')).length) + .toBe(1); + }); + + test('hydration never queries before auth is set up', async ({ page }) => { + const websocket = recordWebSocket(page); + await page.goto('/tests/convex-load-auth'); + await expect(page.getByTestId('hydrated')).toContainText('true', { timeout: 10000 }); + // SSR data is shown right away — no loading state after hydration either. + await expect(page.getByTestId('data')).toBeVisible(); + await expect(page.getByTestId('loading')).not.toBeVisible(); + await expect.poll(() => websocket.events.some((e) => e.type === 'Authenticate')).toBe(true); + await expect + .poll(() => websocket.queryEvents(withMuteWord('__e2e_auth_hydration__')).length) + .toBeGreaterThan(0); + + const firstAuthenticate = websocket.events.findIndex((e) => e.type === 'Authenticate'); + const firstQuery = websocket.events.findIndex( + (e) => e.type !== 'Authenticate' && withMuteWord('__e2e_auth_hydration__')(e) + ); + expect(firstQuery).toBeGreaterThan(firstAuthenticate); + }); + + test('hydration opens exactly one subscription per query', async ({ page }) => { + const websocket = recordWebSocket(page); + await page.goto('/tests/convex-load-release/a'); + await expect(page.getByTestId('hydrated')).toContainText('true', { timeout: 5000 }); + await expect + .poll(() => websocket.queryEvents(withMuteWord('__e2e_release_a__')).length) + .toBe(1); + await page.waitForTimeout(1000); + + expect(websocket.queryEvents(withMuteWord('__e2e_release_a__')).map((e) => e.type)).toEqual([ + 'Add' + ]); + }); + + test('layouts, server layouts and parent(): embeds exactly the universal results', async ({ + page + }) => { + const websocket = recordWebSocket(page); + const response = await page.goto('/tests/convex-load-nested'); + const html = (await response?.text()) ?? ''; + + expect(html).toContain('__e2e_nested_layout__'); + expect(html).toContain('__e2e_nested_page__'); + expect(html).not.toContain('__e2e_nested_server_private__'); + + await expect(page.getByTestId('hydrated')).toContainText('true', { timeout: 5000 }); + await expect(page.getByTestId('layout-data')).toBeVisible(); + await expect(page.getByTestId('data')).toBeVisible(); + await expect + .poll(() => websocket.queryEvents(withMuteWord('__e2e_nested_page__')).length) + .toBe(1); + await page.waitForTimeout(1000); + + // Each universal query: one subscription, no Add/Remove churn. + for (const marker of ['__e2e_nested_layout__', '__e2e_nested_page__']) { + expect(websocket.queryEvents(withMuteWord(marker)).map((e) => e.type)).toEqual(['Add']); + } + }); + + for (const [name, url, predicate] of [ + ['convexLoad', '/tests/convex-load-release/a', withMuteWord('__e2e_release_a__')], + [ + 'convexLoadPaginated', + '/tests/convex-load-paginated', + (e: QueryEvent) => e.udfPath === 'messages:paginatedList' + ] + ] as const) { + test(`${name}: no loading state from SSR through hydration and the live subscription`, async ({ + page + }) => { + // Watch from the very first byte whether a loading state ever renders. + await page.addInitScript(() => { + const w = window as Window & { __sawLoading?: boolean }; + new MutationObserver(() => { + if (document.querySelector('[data-testid="loading"]')) w.__sawLoading = true; + }).observe(document, { childList: true, subtree: true }); + }); + const websocket = recordWebSocket(page); + + await page.goto(url); + await expect(page.getByTestId('hydrated')).toContainText('true', { timeout: 5000 }); + // The live subscription is up and has delivered its first update. + await expect.poll(() => websocket.queryEvents(predicate).length).toBe(1); + await page.waitForTimeout(1000); + + await expect(page.getByTestId('data')).toBeVisible(); + expect( + await page.evaluate(() => (window as Window & { __sawLoading?: boolean }).__sawLoading) + ).toBeUndefined(); + }); + } + + test('embedded data cannot inject scripts', async ({ page, request }) => { + const author = '__e2e_hydration_xss__'; + const mutation = (path: string, args: Record) => + request.post(`${convexUrl()}/api/mutation`, { data: { path, args, format: 'json' } }); + await mutation('messages:send', { + author, + body: '