Skip to content

Commit 48c2ed4

Browse files
committed
fix(router): defer navigation until hydration finishes
Queue location writes while server DOM is being hydrated instead of forcing hydration to end. Preserve write order and drop queued navigation when the router unmounts. Cover early link clicks, composed search updates and disposal with a streamed SSR fixture hydrated in JSDOM.
1 parent fdbcac6 commit 48c2ed4

4 files changed

Lines changed: 310 additions & 1 deletion

File tree

‎.changeset/hydration-navigation.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/router": patch
3+
---
4+
5+
Wait for hydration to finish before applying client navigation. Early link clicks no longer interrupt pending server-rendered content. Queued URL updates keep their order and are discarded if the router unmounts.

‎src/routers/factory.tsx‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,8 @@ function createIntegration(
284284
let committing = false;
285285
// Written, not yet in history (see `RouterIntegration.inflight`).
286286
let inflight: LocationChange | undefined;
287+
let hydrationWrites: LocationWrite[] | undefined;
288+
onCleanup(() => (hydrationWrites = undefined));
287289
const wrap = (value: string | LocationChange) => (typeof value === "string" ? { value } : value);
288290
const [read, write] = createSignal(wrap(history.get()), {
289291
equals: (a, b) => a.value === b.value && a.state === b.state && a._navigation === b._navigation,
@@ -293,7 +295,23 @@ function createIntegration(
293295
const signal: RouterIntegration["signal"] = [
294296
read,
295297
(next: LocationWrite) => {
296-
if (sharedConfig.registry && !sharedConfig.done) sharedConfig.done = true;
298+
if (hydrationWrites) {
299+
hydrationWrites.push(next);
300+
return;
301+
}
302+
if (sharedConfig.isHydrationInProgress?.()) {
303+
// Pending boundaries must claim their server DOM before routes change.
304+
hydrationWrites = [next];
305+
sharedConfig.onHydrationEnd(() =>
306+
queueMicrotask(() => {
307+
// Hydration can also end during disposal; let cleanups run first.
308+
const writes = hydrationWrites;
309+
hydrationWrites = undefined;
310+
writes?.forEach(write => signal[1](write));
311+
})
312+
);
313+
return;
314+
}
297315
// What the write resolved to, or undefined when there was nothing to
298316
// write (see `resolveLocationWrite`).
299317
let written: LocationChange | undefined;
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import { createMemo, Loading, sharedConfig } from "solid-js";
2+
import { isServer } from "@solidjs/web";
3+
import { createRouter, query, useNavigate, useSearchParams } from "../../src/index.js";
4+
5+
export function createApp() {
6+
let release!: (value: string) => void;
7+
const pending = new Promise<string>(resolve => (release = resolve));
8+
const home = query(() => (isServer ? pending : Promise.resolve("Home ready")), "hydration-home");
9+
const destination = query(async () => "Destination ready", "hydration-destination");
10+
let controls!: {
11+
navigate: ReturnType<typeof useNavigate>;
12+
setSearch: ReturnType<typeof useSearchParams>[1];
13+
};
14+
15+
function Home() {
16+
const data = createMemo(() => home());
17+
return (
18+
<main>
19+
<h1>{data()}</h1>
20+
<a href="/destination">Destination</a>
21+
</main>
22+
);
23+
}
24+
25+
function Destination() {
26+
const data = createMemo(() => destination(), { deferStream: true });
27+
return (
28+
<main>
29+
<h1>{data()}</h1>
30+
<a href="/">Home</a>
31+
</main>
32+
);
33+
}
34+
35+
const Router = createRouter({
36+
routes: [
37+
{ path: "/", component: Home },
38+
{ path: "/destination", component: Destination }
39+
],
40+
scrollRestoration: false
41+
});
42+
43+
function App() {
44+
return (
45+
<Router>
46+
{props => {
47+
controls = { navigate: useNavigate(), setSearch: useSearchParams()[1] };
48+
return (
49+
<Loading
50+
fallback={
51+
<main>
52+
<h1>Loading...</h1>
53+
<a href="/destination">Destination</a>
54+
</main>
55+
}
56+
>
57+
{props.children}
58+
</Loading>
59+
);
60+
}}
61+
</Router>
62+
);
63+
}
64+
65+
return { App, release: () => release("Home ready"), controls: () => controls, sharedConfig };
66+
}
Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
// @vitest-environment node
2+
import { createRequire } from "node:module";
3+
import { fileURLToPath } from "node:url";
4+
import { build, createServer, type Plugin, type ViteDevServer } from "vite";
5+
import solidPlugin from "@solidjs/vite-plugin";
6+
import { vi } from "vitest";
7+
8+
const { JSDOM, VirtualConsole } = createRequire(import.meta.url)("jsdom");
9+
const root = fileURLToPath(new URL("../../", import.meta.url));
10+
const serverEntry = `${root}test/fixtures/hydration-server.tsx`;
11+
const clientEntry = `${root}test/fixtures/hydration-client.tsx`;
12+
13+
// Compile the same fixture for SSR and hydration without changing the posture
14+
// of the ordinary component tests. The generated entries stay in memory.
15+
const entries: Plugin = {
16+
name: "hydration-test-entries",
17+
resolveId(id) {
18+
if (id === serverEntry || id === clientEntry) return id;
19+
},
20+
load(id) {
21+
if (id === clientEntry)
22+
return `
23+
import { hydrate } from "@solidjs/web";
24+
import { createApp } from "./hydration-navigation";
25+
const app = createApp();
26+
const dispose = hydrate(() => <app.App />, document.getElementById("app"));
27+
globalThis.hydrationTest = { ...app, dispose };
28+
`;
29+
if (id === serverEntry)
30+
return `
31+
import { createRequestEvent, generateHydrationScript, renderToStream } from "@solidjs/web";
32+
import { provideRequestEvent } from "@solidjs/web/storage";
33+
import { createApp } from "./hydration-navigation";
34+
export function start() {
35+
const event = createRequestEvent(new Request("http://localhost/"));
36+
return provideRequestEvent(event, () => {
37+
const app = createApp();
38+
const chunks = [];
39+
let resolveShell, resolveEnd;
40+
const shell = new Promise(resolve => resolveShell = resolve);
41+
const end = new Promise(resolve => resolveEnd = resolve);
42+
renderToStream(() => <app.App />).pipe({
43+
write(chunk) { chunks.push(String(chunk)); resolveShell(); },
44+
end() { resolveEnd(); }
45+
});
46+
return { chunks, shell, end, release: app.release, bootstrap: generateHydrationScript() };
47+
});
48+
}
49+
`;
50+
}
51+
};
52+
53+
describe("navigation during hydration", () => {
54+
let server: ViteDevServer;
55+
let code: string;
56+
let start: () => {
57+
chunks: string[];
58+
shell: Promise<void>;
59+
end: Promise<void>;
60+
release: () => void;
61+
bootstrap: string;
62+
};
63+
64+
beforeAll(async () => {
65+
server = await createServer({
66+
root,
67+
configFile: false,
68+
logLevel: "silent",
69+
plugins: [entries, solidPlugin({ ssr: true, hot: false, solid: { hydratable: true } })],
70+
ssr: { noExternal: true, resolve: { conditions: ["node"] } },
71+
server: { middlewareMode: true },
72+
appType: "custom"
73+
});
74+
({ start } = await server.ssrLoadModule(serverEntry));
75+
const built = await build({
76+
root,
77+
configFile: false,
78+
logLevel: "silent",
79+
plugins: [entries, solidPlugin({ hot: false, dev: true, solid: { hydratable: true } })],
80+
resolve: { conditions: ["browser", "development"] },
81+
build: {
82+
write: false,
83+
minify: false,
84+
lib: { entry: clientEntry, name: "HydrationTest", formats: ["iife"] },
85+
rolldownOptions: { output: { format: "iife", codeSplitting: false } }
86+
}
87+
});
88+
const output = Array.isArray(built) ? built[0] : built;
89+
if (!("output" in output)) throw new Error("Expected an in-memory build");
90+
const chunk = output.output.find(file => file.type === "chunk");
91+
if (!chunk || chunk.type !== "chunk") throw new Error("Missing hydration entry");
92+
code = chunk.code;
93+
}, 30000);
94+
95+
afterAll(async () => {
96+
await server?.close();
97+
});
98+
99+
async function setup() {
100+
const stream = start();
101+
await stream.shell;
102+
const consumed = stream.chunks.length;
103+
const errors: unknown[] = [];
104+
const console = new VirtualConsole();
105+
console.on("error", (error: unknown) => errors.push(error));
106+
console.on("warn", (warning: unknown) => errors.push(warning));
107+
console.on("jsdomError", (error: unknown) => errors.push(error));
108+
let streaming = true;
109+
const dom = new JSDOM(stream.bootstrap + '<div id="app">' + stream.chunks.join("") + "</div>", {
110+
url: "http://localhost/",
111+
runScripts: "dangerously",
112+
virtualConsole: console,
113+
beforeParse(window: Window) {
114+
// The real document stays open until the stream ends. JSDOM would
115+
// otherwise announce a truncated stream after parsing just its shell.
116+
window.document.addEventListener(
117+
"DOMContentLoaded",
118+
event => streaming && event.stopImmediatePropagation(),
119+
true
120+
);
121+
Object.assign(window, {
122+
scrollTo: () => {},
123+
fetch,
124+
Request,
125+
Response,
126+
Headers,
127+
TextEncoder,
128+
TextDecoder,
129+
ReadableStream,
130+
TransformStream
131+
});
132+
}
133+
});
134+
const { window } = dom;
135+
window.eval(code);
136+
const app = window.hydrationTest;
137+
expect(app.sharedConfig.isHydrationInProgress()).toBe(true);
138+
expect(errors).toEqual([]);
139+
140+
let finished = false;
141+
async function finish() {
142+
if (finished) return;
143+
finished = true;
144+
stream.release();
145+
await stream.end;
146+
const fragment = window.document.createElement("div");
147+
fragment.innerHTML = stream.chunks.slice(consumed).join("");
148+
const scripts = [...fragment.querySelectorAll("script")] as HTMLScriptElement[];
149+
window.document.body.append(...fragment.childNodes);
150+
for (const script of scripts) window.eval(script.textContent);
151+
streaming = false;
152+
window.document.dispatchEvent(new window.Event("DOMContentLoaded"));
153+
await vi.waitFor(() => expect(app.sharedConfig.isHydrationInProgress()).toBe(false));
154+
await new Promise<void>(resolve => setImmediate(resolve));
155+
}
156+
157+
return { dom, window, app, errors, finish };
158+
}
159+
160+
test("an early link click waits for the stream and leaves the destination interactive", async () => {
161+
const { dom, window, app, errors, finish } = await setup();
162+
try {
163+
const click = new window.MouseEvent("click", { bubbles: true, cancelable: true, button: 0 });
164+
window.document.querySelector("a").dispatchEvent(click);
165+
expect(click.defaultPrevented).toBe(true);
166+
expect(app.sharedConfig.isHydrationInProgress()).toBe(true);
167+
expect(window.location.pathname).toBe("/");
168+
169+
await finish();
170+
await vi.waitFor(() => expect(window.location.pathname).toBe("/destination"));
171+
expect(window.document.querySelector("h1").textContent).toBe("Destination ready");
172+
expect(window.document.querySelector('template[id^="pl-"]')).toBeNull();
173+
window.document.querySelector("a").click();
174+
await vi.waitFor(() => expect(window.location.pathname).toBe("/"));
175+
expect(window.document.querySelector("h1").textContent).toBe("Home ready");
176+
expect(errors).toEqual([]);
177+
} finally {
178+
await finish();
179+
app.dispose();
180+
dom.window.close();
181+
}
182+
});
183+
184+
test("queued navigation and search updates keep their order", async () => {
185+
const { dom, window, app, errors, finish } = await setup();
186+
try {
187+
const { navigate, setSearch } = app.controls();
188+
navigate("/destination", { scroll: false });
189+
setSearch({ a: "1" });
190+
setSearch({ b: "2" });
191+
app.sharedConfig.onHydrationEnd(() => setSearch({ c: "3" }));
192+
expect(app.sharedConfig.isHydrationInProgress()).toBe(true);
193+
expect(window.location.pathname).toBe("/");
194+
await finish();
195+
await vi.waitFor(() =>
196+
expect(window.location.pathname + window.location.search).toBe("/destination?a=1&b=2&c=3")
197+
);
198+
expect(errors).toEqual([]);
199+
} finally {
200+
await finish();
201+
app.dispose();
202+
dom.window.close();
203+
}
204+
});
205+
206+
test("disposing the router drops navigation queued during hydration", async () => {
207+
const { dom, window, app, errors, finish } = await setup();
208+
try {
209+
app.controls().navigate("/destination", { scroll: false });
210+
app.dispose();
211+
await finish();
212+
expect(window.location.pathname).toBe("/");
213+
expect(window.document.getElementById("app").childNodes).toHaveLength(0);
214+
expect(errors).toEqual([]);
215+
} finally {
216+
await finish();
217+
dom.window.close();
218+
}
219+
});
220+
});

0 commit comments

Comments
 (0)