Repository navigation
feat(instrumentation): pass a router transition start event with instrumentationClientRouterTransitionEvents - #4910
Conversation
|
/bigbonk review for issues |
@vinext/cloudflare
create-vinext-app
@vinext/types
vinext
@cloudflare/workers-response-store
commit: |
| if (process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS) { | ||
| setRouterTransitionFromRoutesResolver(() => | ||
| hasBrowserRouterState() | ||
| ? resolveRouterTransitionFromRoutes(getBrowserRouterState(), getBrowserRouteManifest()) |
There was a problem hiding this comment.
The resolver can run before the manifest exists. main() only starts loadNavigationRuntimeRouteManifest() fire-and-forget, while notifyAppRouterTransitionStart() runs before navigation awaits that load. On a first interaction under a slow manifest-chunk fetch, this passes null here and resolveRouteSourcePath falls back to concrete URLs (for example /blog/hello instead of /blog/[slug]) and loses slot/interception source paths. When this feature is enabled, make the manifest available before transition hooks can fire.
There was a problem hiding this comment.
Fixed in e4783fc: with instrumentationClientRouterTransitionEvents on, main() now awaits the manifest load it already starts before it hydrates (the fetch still overlaps reading the initial RSC stream). Nothing can start a client transition before hydration (Link, router hooks and popstate handling are wired by bootstrapHydration), so the resolver always sees the manifest. The primary route no longer reads the manifest at all (see the next thread). Without the flag, the await is dropped at build time and startup is unchanged.
There was a problem hiding this comment.
Update, 043cf1b: I reverted the pre-hydration manifest await. With the flag on in app-basic it put the manifest back on the hydration path, which #3957 deliberately removed, and route-manifest-chunk.spec.ts ("an intercepted navigation started before the route manifest loads waits for it") failed in app-router-isr-prod. I won't change hydration timing for an experimental instrumentation field.
The rest of this round's fix makes the remaining gap small. The primary route now comes from the committed payload's sourcePage and never reads the manifest. Only a transition that starts before the manifest chunk arrives (a first interaction under a slow chunk fetch) reports an active slot as its slot directory, not the slot sub-page or intercepting page. That's documented on the resolver and under Known limitations in the PR body.
| ? resolveInterceptionSourcePagePath(interception, null, routeManifest) | ||
| : null; | ||
|
|
||
| const primaryRoutePath = routePathFromId(interception?.sourceRouteId ?? state.routeId); |
There was a problem hiding this comment.
This derives the primary route from URL identity rather than the committed rendered tree. That is wrong for states this router already represents separately: a route miss has sourcePage === null and must report /_not-found, while sibling/whole interceptions deliberately commit with interception: null but retain an interception-marker sourcePage; they currently report the requested target pattern instead. Include the committed elements/source-page metadata in this resolver and derive the primary source path from it.
There was a problem hiding this comment.
Fixed in e4783fc: the primary route now comes from the committed payload's sourcePage metadata (the source segments Next.js carries in its router state), not from the URL. A route miss (sourcePage === null) reports /_not-found. A sibling intercept reports its own page (/gallery/(.)photos/[id]) whether or not interception is set. A whole intercepting route (wholeInterceptionSource) reports the slot owner's default as the primary route, plus the intercepted slot, which matches Next's tree (children __DEFAULT__, slot = intercepting page). Unit tests cover all three, and each one fails on the previous resolver.
| const slot = AppElementsWire.parseElementKey(binding.slotId); | ||
| if ( | ||
| slot?.kind !== "slot" || | ||
| slot.name === "children" || |
There was a problem hiding this comment.
Skipping every children binding loses the actual primary leaf for synthetic parallel routes. For example, /nested/subroute can have a synthetic children binding in default state, so Next’s tree traversal reports /nested/default; this code instead derives /nested/subroute from state.routeId. Active children can similarly fall through to a catch-all source. Use the children binding to resolve or override the primary route rather than discarding it.
There was a problem hiding this comment.
Fixed in e4783fc: the deepest children binding above the committed source page now decides the primary route. In default/unmatched state it reports <owner>/default (/dashboard/default for a synthetic /dashboard/settings), as Next's __DEFAULT__ segment does. When it's active, the source page is reported.
Declining the catch-all sub-case. A synthetic sub-route whose children fall through to a sibling catch-all is an existing documented limitation of that route (see the "Known limitation" note in routing/app-route-graph.ts: the catch-all already gets empty params). Neither the payload nor the router state records which catch-all rendered, so reporting it would need new route-graph wiring for that limitation, which is outside this PR.
| ) { | ||
| continue; | ||
| } | ||
| if (interception !== null && interception.slotId === binding.slotId) { |
There was a problem hiding this comment.
An intercepted slot is not necessarily represented by the current global state.interception. mergeSlotBindings can preserve a previously rendered binding, including its interceptionId, while the next ordinary payload sets the global interception to null. The intercepted page remains visible, but this condition then falls through to the ordinary/default slot path. Resolve an interception whenever binding.interceptionId identifies one, rather than requiring the transient global proof.
There was a problem hiding this comment.
Fixed in e4783fc: each slot binding now resolves through its own interceptionId first, whatever the latest state.interception says. The target-URL fallback still applies only when the latest interception names that slot. Covered by the new "merge keeps the intercepted slot" assertion (binding with interceptionId, interception: null), which fails on the previous resolver.
|
Review: 4 findings. Posted 4 inline warnings in review #6069539049. |
Performance benchmarksCompared 1 improved · 0 regressed · 6 within ±1.5%
View detailed results and traces 🟢 improvement · 🔴 regression · ⚫ change below 1.5% · paired base/head |
|
44cb38c to
0ae44cb
Compare
|
/bigbonk review for issues |
| fromRoutes: resolveRouterTransitionFromRoutes(), | ||
| prefetchIntent, | ||
| }; | ||
| hooks.onRouterTransitionStart(href, navigationType, event); |
There was a problem hiding this comment.
With instrumentationClientInject, this calls the generated aggregate hook once with one mutable event object, and instrumentation-client-inject.ts then forwards that same object to every injected/user hook. Next.js v16.4.6 constructs the event object inside each callHooks invocation, so each module receives a fresh object and fromRoutes array. An early injected hook can currently mutate either and corrupt what later hooks observe. Rebuild or clone the event per generated fan-out invocation, including fromRoutes, and cover mutation isolation.
There was a problem hiding this comment.
Fixed in 5e5007d: the generated fan-out now passes each hook its own copy of the event, with its own fromRoutes array ({ ...event, fromRoutes: [...event.fromRoutes] }), so a mutation in one inject never reaches a later hook. That matches Next.js building the event inside each callHooks invocation. A null event (flag off) passes through unchanged. New test: "gives each hook its own start event". An inject mutates id and fromRoutes, and the user hook still sees the original values; the test fails on the previous generator.
| "transition", | ||
| // Next.js reports the Link's prefetch prop as the transition's | ||
| // prefetch intent (client/app-dir/link.tsx). | ||
| prefetchProp === false ? "none" : prefetchProp === true ? "full" : "auto", |
There was a problem hiding this comment.
The Link intent reaches navigateClientSide only after the hybrid ownership branch above. An App Router Link to a Pages/document-owned local URL exits through location.assign/replace at lines 1688-1698, so it emits no transition event at all. Next.js app-dir Link sends every local URL through navigator.navigate, whose queue calls startRouterTransition before the reducer decides on a hard navigation. Notify before this direct document navigation (with this Link intent), and cover an App-to-Pages Link in a hybrid app.
There was a problem hiding this comment.
Declining for this PR. The early document navigation for a Pages/document-owned URL in a hybrid app skips onRouterTransitionStart on main too, including the legacy two-argument hook without the flag. It's a pre-existing gap in when the hook fires, not in the start event this PR adds. I'll report it as a follow-up.
| const wholeInterceptedSlot = | ||
| metadata.wholeInterceptionSource === null | ||
| ? null | ||
| : (state.slotBindings.find((binding) => { |
There was a problem hiding this comment.
Selecting the first active non-children binding does not identify the intercepted slot. A whole-intercept payload may retain another mounted active slot; bindings are normalized by slotId, so an active @aside can precede the intercepted @modal. This then reports the intercepting source under @aside and treats @modal as an ordinary route. Resolve the slot from interception/source metadata (or preserve its identity explicitly) and add a case with a retained active sibling slot.
There was a problem hiding this comment.
Fixed in 5e5007d: every active, non-children slot whose owner prefixes the source page is now a candidate. The resolver picks the one whose computed @slot/... path matches one of the manifest's interceptions for that slot, and falls back to the first candidate only when nothing matches (or before the manifest loads). New assertion: a kept active @aside sorts before @modal, and the result is still ["/gallery/default", "/gallery/@aside", "/gallery/@modal/(.)photos/[id]"]. It fails on the previous resolver.
|
Since last review: 4 resolved, 0 still open, 3 new. Posted 3 inline warnings in review #6069737446. |
e4783fc to
3938247
Compare
|
/bigbonk review for issues |
|
/bigbonk review for issues |
| } | ||
| const activeRoutePath = routePathFromId(binding.activeRouteId); | ||
| const activeRoute = | ||
| activeRoutePath === null ? null : matchManifestRoute(activeRoutePath, routeManifest); |
There was a problem hiding this comment.
activeRouteId for ordinary slots is already the manifest route ID: createAppPageSlotBindings builds it from encodeRouteId(options.routePath, null), where callers pass the route pattern. Reinterpreting that pattern as an href can select a different sibling route. For example, an active catch-all ID such as route:/shop/:slug+ is a one-segment URL to the trie, so a sibling /shop/:id wins and this then reads the wrong slot binding (reporting the wrong/default fromRoutes path). Look up segmentGraph.routes.get(binding.activeRouteId) first, and reserve URL matching for IDs that are not manifest IDs, such as concrete interception targets.
There was a problem hiding this comment.
Fixed in e2d69d3: an active slot's route is now looked up directly by segmentGraph.routes.get(binding.activeRouteId). Ordinary slots carry route:<pattern>, since createAppPageSlotBindings gets route.pattern as routePath. Only an id that isn't a manifest key falls back to URL matching. New test: "reads an active slot's route by its manifest id, not as a URL" adds a sibling /shop/:id next to /shop/[[...slug]] with a @panel slot. It reports /shop/@panel/[[...slug]] and fails on the previous resolver (which reported the sibling's default).
The two findings listed as still open at 043cf1b were addressed in 5e5007d: per-hook event copies and manifest-based whole-intercept slot selection. The hybrid App→Pages Link case was declined there as a pre-existing gap.
|
Since last review: 1 resolved, 2 still open, 1 new. Posted 1 new inline warning. The two existing warnings remain at exact head |
|
/bigbonk review for issues |
e2d69d3 to
689009e
Compare
|
Review: 3 findings.
|
8a991c4 to
c9c908b
Compare
|
/bigbonk review for issues |
|
Thanks. Fixed in f8a2f92:
Declined:
|
|
/bigbonk review for issues |
|
Since last review: 0 resolved, 3 still open, 0 new.
Head |
…rumentationClientRouterTransitionEvents
…oad the manifest before transitions
… the whole-intercepted slot
…ample each hook's timestamp
|
Rebased onto #4909's |
f8a2f92 to
538b466
Compare
|
/bigbonk review for issues |
| " Reflect.apply(hook, hooks, [", | ||
| " url,", | ||
| " type,", | ||
| " event == null", |
There was a problem hiding this comment.
This leaves the rich-event marker in flag-disabled bundles whenever instrumentationClientInject generates this aggregate hook. The exported function can receive an arbitrary event, so the bundler cannot prove this branch unreachable from the caller’s define and fromRoutes remains in the client chunk. Next.js explicitly tests that no client chunk contains fromRoutes when the flag is off (test/production/app-dir/instrumentation-client-dce/instrumentation-client-dce.test.ts). Gate this generated cloning branch with __NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS (or generate flag-specific source) so the payload is actually dead-code-eliminated.
There was a problem hiding this comment.
Fixed in 117fad3. The generated event copy now checks process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS, which vinext defines as a raw boolean. With the flag off, the conditional folds to event and the copy (fromRoutes) drops out. New test, ported from Next's instrumentation-client-dce: it minifies the generated module with the define applied and checks that fromRoutes is present with the flag on and absent with it off. It fails on the previous head. The dev e2e (instrumentation-client-transition-events.spec.ts, flag on) still passes.
| } | ||
|
|
||
| slots.sort((left, right) => left.localeCompare(right)); | ||
| return [primary, ...slots]; |
There was a problem hiding this comment.
This always invents and prepends a primary route, but supported layout-only routes can have only named parallel branches and no children leaf. For example, the existing /parallel-nested/home fixture has no page.tsx; Next.js getActiveRoutePaths walks its @parallelB leaf only, while this returns an extra /parallel-nested/home before /parallel-nested/home/@parallelB/default. Use the committed route/manifest pageId plus the absence of a children binding to make the primary entry optional, and cover a layout-only slot route.
There was a problem hiding this comment.
Fixed in 117fad3 for the route Next actually renders, /parallel-nested/home/nested. Next 16.4 turns explicitParallelRouteChildren on by default, so a layout composed only of named slots gets no children branch. vinext records that as an unmatched synthetic children binding, which now omits the primary entry: the result is ["/parallel-nested/home/@parallelB/nested"]. The new test uses the checked-in parallel-nested fixture's manifest and fails on the previous head.
I'm not covering bare /parallel-nested/home. In Next it isn't a route, because a slot's default.tsx creates no app path, so there is no Next value for fromRoutes to match. vinext serving that URL at all is a separate, pre-existing routing difference, outside this PR.
|
Review: 2 findings. Posted 2 inline warnings in review #6070198948. |
… omit children a layout doesn't declare
|
/bigbonk review for issues |
| // route reports only its slots (Next.js explicitParallelRouteChildren). | ||
| primary = | ||
| children === null || children.binding.state === "active" | ||
| ? joinSourcePath(sourceSegments) |
There was a problem hiding this comment.
When a slot-only navigation preserves an existing active children branch, this uses the latest payload’s sourcePage rather than the active children binding. For example, the existing /parallel-layouts/settings → /parallel-layouts/modal flow preserves the settings children branch (tests/e2e/app-router/advanced.spec.ts:137-147), while the merged metadata comes from the modal payload, so the next transition reports /parallel-layouts/modal instead of the still-rendered /parallel-layouts/settings. Resolve the active primary path from children.binding.activeRouteId and the manifest, as the named-slot path does.
There was a problem hiding this comment.
Fixed in 99f24ba. When the deepest children binding is active and names a different route from the latest payload's routeId (the merge kept the previous binding), the primary entry now comes from that binding's route id, converted to Next's source form with patternToNextFormat. Otherwise it still uses the committed source page. I checked this in the dev app: after /parallel-layouts/settings → /parallel-layouts/modal, the next transition now reports ["/parallel-layouts/settings", "/parallel-layouts/@bar/modal", "/parallel-layouts/@foo/default"] instead of /parallel-layouts/modal. New unit test: "reports the children route a slot-only navigation kept". It fails on the previous head.
|
Since last review: 2 resolved, 0 still open, 1 new. Posted 1 inline warning. |
|
/bigbonk review for issues |
| : null; | ||
| primary = | ||
| childrenRoutePath !== null | ||
| ? patternToNextFormat(childrenRoutePath) |
There was a problem hiding this comment.
This still returns a concrete URL for a preserved dynamic children branch. The RSC entry calls buildPageElements(..., cleanPathname, ...), and createAppPageSlotBindings stores that render identity in activeRouteId, so a preserved /members/[id] branch carries route:/members/7; patternToNextFormat('/members/7') remains /members/7 instead of Next's /members/[id]. Resolve this ID through routeManifest (the same direct-ID-then-URL-match path used by resolveSlotSourcePath) and derive the source pattern from the matched route. The new test masks this by supplying the pattern-shaped route:/blog/:slug rather than a concrete dynamic ID.
There was a problem hiding this comment.
Fixed in 507e952. The kept children binding's activeRouteId now goes through the same manifest lookup as named slots (resolveManifestRoute): by id first, then by matching the concrete URL. The primary entry is derived from the matched route's patternParts, so a kept route:/members/7 reports /members/[id]. If the manifest hasn't loaded, it falls back to the committed source page. The test now uses a concrete id (route:/blog/hello → /blog/[slug]) and fails on the previous head. I also corrected the comment in resolveSlotSourcePath that said active route ids are pattern-shaped.
|
Since last review: 0 resolved, 1 still open, 0 new. Posted 1 inline warning on preserved dynamic child routes. |
|
/bigbonk review for issues |
| prefetchIntent: RouterTransitionPrefetchIntent | null = null, | ||
| ): void { | ||
| const hooks = getClientInstrumentationHooks(); | ||
| if (typeof hooks?.onRouterTransitionStart !== "function") return; |
There was a problem hiding this comment.
With instrumentationClientInject, this guard sees the generated aggregate function even when none of the injected/user modules currently exports a hook. Next.js v16.4.6 checks the raw modules with .some(...) before incrementing nextTransitionId or resolving fromRoutes. Consequently, transitions before a late CommonJS hook is installed consume IDs (and can run/fail the resolver) that Next skips, so the first event that hook observes can be ...-2 instead of ...-1. Give the aggregate a live has-hook probe or defer rich-event creation into its fan-out.
|
Since last review: 1 resolved, 0 still open, 1 new. Posted 1 inline warning. |
Stacked on #4909.
Found by the Next.js v16.4.6 deploy suite (run 45649241516): the
router transition start contextgroup oftest/e2e/instrumentation-client-hook/instrumentation-client-hook.test.ts(5 tests) failed.What Next.js does
With
experimental.instrumentationClientRouterTransitionEvents,onRouterTransitionStart(url, type, event)receives a start event as its third argument instead ofnull. Ref:packages/next/src/client/components/router-transition.tsandclient/router-transition-types.ts.id:${Date.now().toString(36)}-${counter.toString(36)}.timestamp:performance.timeOrigin + performance.now().fromRoutes: source route patterns of the tree being left, fromgetActiveRoutePaths.@slot/default./gallery/@modal/(.)photos/[id].prefetchIntent: the Link's prop (prefetch={false}→"none",true→"full", otherwise"auto").router.push/replaceand back/forward sendnull.The flag reaches the client as
process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS, a raw boolean (build/define-env.ts). Building the event is inside the per-hooktry, so a failure is logged asAn instrumentation-client router transition hook failed.Fix
experimental.instrumentationClientRouterTransitionEventsis resolved (defaultfalse) and defined for the client as the same raw boolean. Without the flag, the event path drops out of the bundle.notifyAppRouterTransitionStart(client/instrumentation-client-state.ts) builds the event inside the try.fromRoutescomes from a resolver that the App Router browser entry registers only when the flag is on.fromRoutesresolver: the newserver/app-browser-transition-routes.tsbuildsfromRoutesfrom the committed tree, as Next.js walks its committed router state.sourcePage(the source segments vinext already sends, as Next.js does for__internal_src_page). A URL that matched no route reports/_not-found. A sibling intercept reports its own page. When the deepest children slot shows its default (a synthetic parallel sub-route), it reports<owner>/default. A whole intercepting route reports the owner'sdefaultplus the intercepted slot.interceptionId, so an intercepted slot that a merge kept still reports the intercepting page. Active slot sub-pages use the manifest slot binding's rawrouteSegments.sourcePagePath: the intercepting page's directory with route groups removed, built from the existingsourcePageSegments.<Link>passes itsprefetchprop asprefetchIntentthroughnavigateClientSide. Other callers passnull.This is App Router only, as in Next.js. The server and worker entries are unaffected.
Regression tests
tests/e2e/app-router/instrumentation-client-transition-events.spec.tsports the 5 Next.js tests and adds a back/forward case. It runs inapp-router(dev) andapp-router-isr-prod. It uses new pages undertests/fixtures/app-basic/app/instrumentation-client/transition-events, a copy of the Next.js fixture. app-basic now enables the flag, following thegestureTransitionprecedent, so the fix(instrumentation): read instrumentationClientInject hooks per transition and isolate their errors #4909 inject spec checks that the injected hook receives the event.tests/app-browser-transition-routes.test.tsunit-tests the resolver against the scanned fixture: patterns, catch-alls, groups, slots, the default slot, interception (including a merged intercepted slot), route misses, sibling and whole intercepts (including an active sibling slot that a merge kept), and a synthetic sub-route's children default.tests/instrumentation.test.tscovers the event shape and the logged resolver failure.tests/next-config.test.tscovers the flag.With the pre-fix source (
git restore --source=<#4909 head> -- packages/vinext/src, then rebuild), the 6 e2e tests fail in dev. With the fix they pass in dev and prod.Targeted
vp test runpasses for these files:tests/app-browser-transition-routes.test.tstests/instrumentation.test.tstests/app-route-graph.test.tstests/entry-templates.test.tstests/browser-route-manifest.test.tstests/next-config.test.tsvp checkis clean.Deploy suite (local,
ds-run.sh)instrumentation-client-hook.test.ts: 8/17 on main, 12/17 on fix(instrumentation): read instrumentationClientInject hooks per transition and isolate their errors #4909, 17/17 here. The 5router transition start contexttests flip fail→pass, with no pass→fail.instrumentation-client-hook.test.ts: 6/6 pass on this branch, with no pass→fail. That version has norouter transition start contexttests.Declined
<Link>to a Pages- or document-owned URL navigates the document without callingonRouterTransitionStart, where Next.js calls it first. The same is true on main for the legacy hook, so it's a separate, pre-existing gap.route-manifest-chunk.spec.ts.routing/app-route-graph.ts(the catch-all already gets empty params), and the router state doesn't record which catch-all rendered.Performance
Without the flag, nothing runs on the navigation path, because the event and resolver code is behind the compile-time define. The per-interception
sourcePagePathadds a few bytes to the lazily loaded route-manifest chunk. CI's paired perf comparison covers build time and dev cold start.