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
93 changes: 88 additions & 5 deletions packages/vinext/src/shims/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ function renderPagesRouterElement(
}

cancelPreviousRenderCommit();
commitRouterSnapshot();

return new Promise<void>((resolve, reject) => {
const cancel = () => {
Expand Down Expand Up @@ -443,6 +444,12 @@ type PagesRouterRuntimeState = {
routerDidNavigate: boolean;
deprecatedEventBridgeInstalled: boolean;
pagesRouterReady: boolean;
/**
* The router snapshot of the last committed router state change (see
* `commitRouterSnapshot`). `token` grows by one per commit, so the provider
* can tell a newer commit from the state it already holds.
*/
committedRouterSnapshot: CommittedRouterSnapshot | null;
publicRouter?: Record<string, unknown>;
};

Expand Down Expand Up @@ -473,6 +480,7 @@ function createPagesRouterRuntimeState(): PagesRouterRuntimeState {
routerDidNavigate: false,
deprecatedEventBridgeInstalled: false,
pagesRouterReady: typeof window === "undefined" || !shouldDeferInitialPagesRouterReady(),
committedRouterSnapshot: null,
};
}

Expand Down Expand Up @@ -3218,10 +3226,21 @@ function stripHash(url: string): string {
return i === -1 ? url : url.slice(0, i);
}

/**
* `detail` of the `vinext:navigate` events the router dispatches. Every such
* navigation has already committed its router snapshot (`commitRouterSnapshot`).
* A string, not an object: the client entry and page chunks can each evaluate
* their own `next/router` instance, and the provider must recognise an event
* dispatched by any of them.
*/
const ROUTER_NAVIGATE_EVENT_DETAIL = "vinext.routerStateCommitted";

/** Notify in-page listeners (e.g. useRouter hooks) that navigation occurred. */
function dispatchNavigateEvent(): void {
notifyNextNavigationPagesContext();
window.dispatchEvent(new CustomEvent("vinext:navigate"));
window.dispatchEvent(
new CustomEvent("vinext:navigate", { detail: ROUTER_NAVIGATE_EVENT_DETAIL }),
);
}

/**
Expand Down Expand Up @@ -3701,6 +3720,7 @@ async function performNavigation(
: (redirectBrowserHref ?? credentialedDisplayHref ?? full),
navState,
);
commitRouterSnapshot();
if (doScroll) scrollToHashTarget(extractHash(resolved));
onStateUpdate?.();
routerEvents.emit("hashChangeComplete", eventUrl, { shallow });
Expand Down Expand Up @@ -3831,6 +3851,7 @@ async function performNavigation(
if (result === "failed") return false;
} else {
emitBeforeHistoryChange();
commitRouterSnapshot();
// Shallow navigations skip the render-commit path, so apply the scroll
// reset synchronously here — before routeChangeComplete. This matches the
// non-shallow path, where the x/y reset runs inside the render-commit
Expand Down Expand Up @@ -3935,17 +3956,77 @@ export function useRouter(): NextRouter {
);
}

type RouterSnapshot = ReturnType<typeof getRouterSnapshot>;

type CommittedRouterSnapshot = {
token: number;
snapshot: RouterSnapshot;
};

type RouterSnapshotState = {
snapshot: RouterSnapshot;
// The `committedRouterSnapshot` token this state already accounts for.
commitToken: number;
};

function getCommittedRouterSnapshotToken(): number {
return routerRuntimeState.committedRouterSnapshot?.token ?? 0;
}

/**
* Record the router state at the moment a change commits, like Next.js's
* `Router#set()` assigning `this.state` (packages/next/src/shared/lib/router/router.ts).
* A render-backed navigation calls this once its history entry and
* `__NEXT_DATA__` are committed, right before `root.render()`; shallow and
* hash-only changes call it after their history update, and the ready
* transition when it flips the ready bit. The provider only ever shows a
* committed snapshot, never the live location: on popstate the browser moves
* `location` before the route is resolved, a traversal rejected by
* `beforePopState` never commits, and the location may move again before a
* completed navigation dispatches `vinext:navigate`.
*/
function commitRouterSnapshot(): void {
routerRuntimeState.committedRouterSnapshot = {
token: getCommittedRouterSnapshotToken() + 1,
snapshot: getRouterSnapshot(),
};
}

function takeRouterSnapshot(): RouterSnapshotState {
return { snapshot: getRouterSnapshot(), commitToken: getCommittedRouterSnapshotToken() };
}

/** Adopt a router state commit newer than the provider's state, if there is one. */
function adoptCommittedRouterSnapshot(prev: RouterSnapshotState): RouterSnapshotState {
const committed = routerRuntimeState.committedRouterSnapshot;
if (committed === null || committed.token === prev.commitToken) return prev;
return { snapshot: committed.snapshot, commitToken: committed.token };
}

function PagesRouterProvider({ children }: { children: ReactNode }): ReactElement {
const [{ pathname, query, asPath, isReady }, setState] = useState(getRouterSnapshot);
const [routerState, setState] = useState(takeRouterSnapshot);
// A client navigation records its route snapshot and then calls
// root.render(), which re-renders this provider with its old state. Adopt the
// committed snapshot during render, before any child reads the context, so
// the new page's first render already sees its route, as in Next.js.
const currentRouterState = adoptCommittedRouterSnapshot(routerState);
if (currentRouterState !== routerState) setState(currentRouterState);
const { pathname, query, asPath, isReady } = currentRouterState.snapshot;

// Popstate is handled by the Pages Router client entry via
// installPagesRouterRuntime() so beforePopState() is consistently enforced
// regardless of hook consumers. Keep URL snapshot subscriptions at the
// provider boundary so many useRouter() calls share one router state and one
// vinext:navigate listener.
useEffect(() => {
const onNavigate = ((_e: CustomEvent) => {
setState(getRouterSnapshot());
// The router's own navigations committed their snapshot already (a
// render-backed one was adopted during render, so this only picks up
// shallow and hash-only changes). Never re-read the live location for
// them: it may have moved since. An event dispatched outside the router
// has no commit, so it records the live state, as before.
const onNavigate = ((e: CustomEvent) => {
if (e.detail !== ROUTER_NAVIGATE_EVENT_DETAIL) commitRouterSnapshot();
Comment thread
alcora-dev[bot] marked this conversation as resolved.
Resolved
setState(adoptCommittedRouterSnapshot);
}) as EventListener;
window.addEventListener("vinext:navigate", onNavigate);
let cancelled = false;
Expand All @@ -3954,7 +4035,8 @@ function PagesRouterProvider({ children }: { children: ReactNode }): ReactElemen

const becameReady = markPagesRouterReady();
if (becameReady) {
setState(getRouterSnapshot());
commitRouterSnapshot();
setState(adoptCommittedRouterSnapshot);
notifyNextNavigationPagesContext();
}
}, 0);
Expand Down Expand Up @@ -4192,6 +4274,7 @@ function handlePagesRouterPopState(e: PopStateEvent): void {
// L1381-1403 and L1780). The snapshot stays in sessionStorage, so a later
// non-hash popstate to this entry still restores the saved position.
const hashUrl = browserUrl + window.location.hash;
commitRouterSnapshot();
routerEvents.emit("hashChangeStart", hashUrl, { shallow: false });
scrollToHashTarget(window.location.hash);
routerEvents.emit("hashChangeComplete", hashUrl, { shallow: false });
Expand Down
132 changes: 132 additions & 0 deletions tests/e2e/pages-router/first-render-router.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { test, expect, type Page } from "@playwright/test";

const BASE = "http://localhost:4173";

type RenderRecord = {
query: Record<string, unknown>;
pathname: string;
asPath: string;
location: string;
};

async function takeRenders(page: Page): Promise<RenderRecord[]> {
return page.evaluate(() => {
const w = window as unknown as { __FIRST_RENDER_ROUTER__?: RenderRecord[] };
const renders = w.__FIRST_RENDER_ROUTER__ ?? [];
w.__FIRST_RENDER_ROUTER__ = [];
return renders;
});
}

function expectEveryRenderToSee(renders: RenderRecord[], id: string): void {
expect(renders.length).toBeGreaterThan(0);
for (const render of renders) {
expect(render).toEqual({
query: { id },
pathname: "/first-render-router/[id]",
asPath: `/first-render-router/${id}`,
location: `/first-render-router/${id}`,
});
}
}

// Next.js assigns router state before rendering the new page (Router#set()
// in packages/next/src/shared/lib/router/router.ts), so the first render after
// a client navigation already sees the destination route.
test("useRouter() returns the new route on the first render after client navigation", async ({
page,
}) => {
await page.goto(`${BASE}/first-render-router`);
await page.waitForFunction(() => (window as any).next?.router?.isReady === true);

// <Link> from a static page to a dynamic one.
await page.click('[data-testid="first-render-link"]');
await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("1");
expectEveryRenderToSee(await takeRenders(page), "1");

// router.push between two params of the same dynamic page, which stays mounted.
await page.click('[data-testid="first-render-push"]');
await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("2");
expectEveryRenderToSee(await takeRenders(page), "2");

// Back (popstate) to the previous param.
await page.goBack();
await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("1");
expectEveryRenderToSee(await takeRenders(page), "1");
});

// The provider renders the route the navigation committed, not whatever the
// browser location is when React renders or when the navigation completes. On
// popstate the browser moves `location` before the route is resolved, so the
// live URL must never be mixed with the committed page.
test("useRouter() keeps the committed route if location moves after the commit", async ({
page,
}) => {
await page.goto(`${BASE}/first-render-router/1`);
await page.waitForFunction(() => (window as any).next?.router?.isReady === true);
await takeRenders(page);

await page.evaluate(() => {
const w = window as any;
w.__FIRST_RENDER_NAVIGATED__ = false;
w.next.router.events.on("routeChangeComplete", () => {
// vinext:navigate is dispatched right after routeChangeComplete; let the
// provider's listener run and React commit before declaring it done.
setTimeout(() => {
w.__FIRST_RENDER_NAVIGATED__ = true;
}, 50);
});
const root = w.__VINEXT_ROOT__;
const render = root.render.bind(root);
root.render = (element: unknown) => {
root.render = render;
render(element);
// React renders later, in its own task. Move the URL before it does and
// keep it moved through the navigation's completion.
window.history.replaceState(window.history.state, "", "/first-render-router/1?moved=1");
};
});
await page.click('[data-testid="first-render-push"]');
await page.waitForFunction(() => (window as any).__FIRST_RENDER_NAVIGATED__ === true);

const renders = await takeRenders(page);
expect(renders.length).toBeGreaterThan(0);
for (const render of renders) {
expect({ query: render.query, pathname: render.pathname, asPath: render.asPath }).toEqual({
query: { id: "2" },
pathname: "/first-render-router/[id]",
asPath: "/first-render-router/2",
});
}
await expect(page.locator('[data-testid="first-render-id"]')).toHaveText("2");
});

// The client entry and page chunks can each evaluate their own `next/router`
// instance, so the provider may receive `vinext:navigate` from a router module
// other than its own. Such an event carries the router's marker as a value
// created outside the provider's module, and must still count as a committed
// navigation, never a cue to re-read the live location.
test("useRouter() treats vinext:navigate from another router instance as committed", async ({
page,
}) => {
await page.goto(`${BASE}/first-render-router/1`);
await page.waitForFunction(() => (window as any).next?.router?.isReady === true);
await takeRenders(page);

await page.evaluate(async () => {
window.history.replaceState(window.history.state, "", "/first-render-router/1?moved=1");
window.dispatchEvent(
new CustomEvent("vinext:navigate", { detail: "vinext.routerStateCommitted" }),
);
await new Promise((resolve) => setTimeout(resolve, 50));
});

// Nothing was committed, so the provider has no reason to re-render; any
// render that does happen must still see the committed route.
for (const render of await takeRenders(page)) {
expect({ query: render.query, asPath: render.asPath }).toEqual({
query: { id: "1" },
asPath: "/first-render-router/1",
});
}
});
34 changes: 34 additions & 0 deletions tests/fixtures/pages-basic/pages/first-render-router/[id].tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { useRouter } from "next/router";

type RenderRecord = {
query: Record<string, unknown>;
pathname: string;
asPath: string;
location: string;
};

export const getServerSideProps = async () => ({ props: {} });

export default function FirstRenderRouterItem() {
const router = useRouter();
if (typeof window !== "undefined") {
const w = window as unknown as { __FIRST_RENDER_ROUTER__?: RenderRecord[] };
(w.__FIRST_RENDER_ROUTER__ ??= []).push({
query: { ...router.query },
pathname: router.pathname,
asPath: router.asPath,
location: window.location.pathname,
});
}
return (
<div>
<p data-testid="first-render-id">{String(router.query.id)}</p>
<button
data-testid="first-render-push"
onClick={() => void router.push("/first-render-router/2")}
>
push /first-render-router/2
</button>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import Link from "next/link";

export default function FirstRenderRouterHome() {
return (
<Link href="/first-render-router/1" data-testid="first-render-link">
go to /first-render-router/1
</Link>
);
}
Loading