Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/convexload-hydration-single-subscription.md
Original file line number Diff line number Diff line change
@@ -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 `<head>` 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.
157 changes: 157 additions & 0 deletions e2e/convexLoadHydration.test.ts
Original file line number Diff line number Diff line change
@@ -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 <head>, so it exists before SvelteKit's start script runs the loads.
expect(html.indexOf('data-convex-load')).toBeLessThan(html.indexOf('</head>'));
});

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<string, string>) =>
request.post(`${convexUrl()}/api/mutation`, { data: { path, args, format: 'json' } });
await mutation('messages:send', {
author,
body: '</script><script>window.__convexXss = true</script><!--'
});

try {
// /tests/convex-load lists all messages, including the one above.
const response = await page.goto('/tests/convex-load');
expect(await response?.text()).toContain('data-convex-load');
await expect(page.getByTestId('hydrated')).toContainText('true', { timeout: 5000 });
await expect(page.getByTestId('data')).toBeVisible();

expect(await page.evaluate(() => 'convexXss' in window || '__convexXss' in window)).toBe(
false
);
} finally {
await mutation('messages:deleteByAuthor', { author });
}
});
});
57 changes: 55 additions & 2 deletions e2e/convexLoadRelease.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect, test, type Page } from '@playwright/test';
import { recordWebSocket, withMuteWord, type QueryEvent } from './helpers/websocket.js';

// ---------------------------------------------------------------------------
// convexLoad subscriptions are route-scoped (issue #57): leaving a route
Expand Down Expand Up @@ -107,8 +108,6 @@ test.describe('convexLoad — route-scoped subscriptions', () => {
const subscriptions = trackSubscriptions(page);
await openPage(page, '/tests/convex-load-release/a');
await expect.poll(() => subscriptions.isSubscribed('a')).toBe(true);
// Let hydration settle: universal loads re-run in the browser, and
// convexLoad's initial client.query() briefly subscribes on its own.
await page.waitForTimeout(1000);
const mark = subscriptions.mark();

Expand All @@ -122,3 +121,57 @@ test.describe('convexLoad — route-scoped subscriptions', () => {
expect(subscriptions.isSubscribed('a')).toBe(true);
});
});

test.describe('convexLoad — one subscription per query', () => {
test('client-side navigation opens exactly one subscription', async ({ page }) => {
const websocket = recordWebSocket(page);
await openPage(page, '/tests/convex-load-release/a');
const mark = websocket.mark();

await navigateTo(page, 'b');
await page.waitForTimeout(1000);

// Previously: Add (one-shot query) → Remove → Add (live subscription).
expect(
websocket.queryEvents(withMuteWord('__e2e_release_b__'), mark).map((e) => e.type)
).toEqual(['Add']);
});
});

test.describe('convexLoadPaginated — one subscription per query', () => {
const isPaginatedList = (event: QueryEvent) => event.udfPath === 'messages:paginatedList';

test('hydration opens exactly one subscription', async ({ page }) => {
const websocket = recordWebSocket(page);
await page.goto('/tests/convex-load-paginated');
await expect(page.getByTestId('hydrated')).toContainText('true', { timeout: 5000 });
await expect.poll(() => websocket.queryEvents(isPaginatedList).length).toBeGreaterThan(0);
await page.waitForTimeout(1000);

expect(websocket.queryEvents(isPaginatedList).map((e) => e.type)).toEqual(['Add']);
});

test('client-side navigation opens exactly one subscription', async ({ page }) => {
const websocket = recordWebSocket(page);
await page.goto('/tests');
await expect(page.getByRole('link', { name: /ConvexLoadPaginated/ })).toBeVisible();
const mark = websocket.mark();

// The load awaits the first page, so the new page never renders a loading state.
await page.evaluate(() => {
const w = window as Window & { __sawLoading?: boolean };
new MutationObserver(() => {
if (document.querySelector('[data-testid="loading"]')) w.__sawLoading = true;
}).observe(document.body, { childList: true, subtree: true });
});

await page.getByRole('link', { name: /ConvexLoadPaginated/ }).click();
await expect(page.getByTestId('data')).toBeVisible({ timeout: 10000 });
await page.waitForTimeout(1000);

expect(websocket.queryEvents(isPaginatedList, mark).map((e) => e.type)).toEqual(['Add']);
expect(
await page.evaluate(() => (window as Window & { __sawLoading?: boolean }).__sawLoading)
).toBeUndefined();
});
});
81 changes: 81 additions & 0 deletions e2e/helpers/websocket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { readFileSync } from 'node:fs';
import type { Page } from '@playwright/test';

type QueryArgs = Record<string, unknown>;

export type QueryEvent = {
type: 'Add' | 'Remove';
queryId: number;
udfPath: string;
args: QueryArgs;
};

export type WebSocketEvent = QueryEvent | { type: 'Authenticate' };

type ModifyQuerySet = {
type: 'ModifyQuerySet';
modifications: Array<
| { type: 'Add'; queryId: number; udfPath: string; args: QueryArgs[] }
| { type: 'Remove'; queryId: number }
>;
};

/**
* Record the Convex protocol messages a page sends: query subscriptions
* (Add/Remove, with their function and args) and authentication.
*/
export function recordWebSocket(page: Page) {
const events: WebSocketEvent[] = [];
const addsById = new Map<number, QueryEvent>();

page.on('websocket', (ws) => {
ws.on('framesent', ({ payload }) => {
if (typeof payload !== 'string') return;
const message = JSON.parse(payload) as { type: string };
if (message.type === 'Authenticate') {
events.push({ type: 'Authenticate' });
return;
}
if (message.type !== 'ModifyQuerySet') return;
for (const modification of (message as ModifyQuerySet).modifications) {
if (modification.type === 'Add') {
const add: QueryEvent = {
type: 'Add',
queryId: modification.queryId,
udfPath: modification.udfPath,
args: modification.args[0] ?? {}
};
addsById.set(add.queryId, add);
events.push(add);
} else {
const add = addsById.get(modification.queryId);
if (add) events.push({ ...add, type: 'Remove' });
}
}
});
});

return {
events,
/** Position in the event log, to only look at later events. */
mark: () => events.length,
/** Add/Remove events of queries matching `predicate`, from `since` on. */
queryEvents: (predicate: (event: QueryEvent) => boolean, since = 0) =>
events
.slice(since)
.filter((event): event is QueryEvent => event.type !== 'Authenticate' && predicate(event))
};
}

/** Match queries whose `muteWords` arg contains `marker` (test pages use unique markers). */
export const withMuteWord = (marker: string) => (event: QueryEvent) =>
Array.isArray(event.args.muteWords) && event.args.muteWords.includes(marker);

/** The deployment URL from `.env.local` (or the environment). */
export function convexUrl(): string {
if (process.env.PUBLIC_CONVEX_URL) return process.env.PUBLIC_CONVEX_URL;
const env = readFileSync('.env.local', 'utf8');
const url = env.match(/^PUBLIC_CONVEX_URL=(.+)$/m)?.[1]?.trim();
if (!url) throw new Error('PUBLIC_CONVEX_URL not found in .env.local');
return url;
}
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@
"types": "./dist/sveltekit/server-token.d.ts",
"import": "./dist/sveltekit/server-token.js",
"default": "./dist/sveltekit/server-token.js"
},
"./sveltekit/server/hydration": {
"types": "./dist/sveltekit/hydration-server.d.ts",
"import": "./dist/sveltekit/hydration-server.js",
"default": "./dist/sveltekit/hydration-server.js"
}
},
"peerDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion src/app.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
%sveltekit.head% %convex.hydration%
</head>
<body data-sveltekit-preload-data="hover">
<div>%sveltekit.body%</div>
Expand Down
5 changes: 5 additions & 0 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { convexLoadHydration } from '$lib/sveltekit/hydration-server.js';

// Embed convexLoad results from universal loads in the SSR HTML, so loads that
// re-run during hydration reuse them instead of querying again.
export const handle = convexLoadHydration;
15 changes: 15 additions & 0 deletions src/lib/internal/singleton.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ let _singletonUrl: string | null = null;
// ---------------------------------------------------------------------------
let _deferredSubscriptions: Array<() => void> | null = [];

// Set by the first flush and never reset (not even by closeConvex): loads that
// run before it belong to the initial page hydration.
let _hasFlushedOnce = false;

// Teardown hooks run by closeConvex(), e.g. to dispose route-scoped queries.
// Registered by callers so this core module does not depend on them.
const _closeListeners = new Set<() => void>();
Expand Down Expand Up @@ -59,12 +63,23 @@ export function deferSubscription(fn: () => void): void {
* Safe to call multiple times — subsequent calls are no-ops.
*/
export function flushDeferredSubscriptions(): void {
_hasFlushedOnce = true;
if (_deferredSubscriptions === null) return;
const pending = _deferredSubscriptions;
_deferredSubscriptions = null; // Switch to immediate mode
for (const fn of pending) fn();
}

/**
* Whether the app is still hydrating the initial server-rendered page, i.e.
* `setupConvex()` / `setupAuth()` have not flushed deferred subscriptions yet.
* SvelteKit runs universal `load` functions for the initial page in this window.
* @internal
*/
export function isInitialHydration(): boolean {
return !_hasFlushedOnce;
}

export function getSingletonClient(): ConvexClient | null {
if (_singletonClient?.closed) {
_singletonClient = null;
Expand Down
Loading
Loading