Repository navigation
feat(instrumentation): pass a router transition start event with instrumentationClientRouterTransitionEvents #4910
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
34c7dad
c6cf07e
edaaf0e
1d90ee3
7433131
24ae79c
538b466
117fad3
99f24ba
507e952
3068c5e
7cf1444
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -27,22 +27,87 @@ export function getClientInstrumentationHooks(): ClientInstrumentationHooks | nu | |
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Exported by the generated instrumentationClientInject module: whether any | ||
| * module it fans out to has an onRouterTransitionStart hook right now. | ||
| */ | ||
| export const HAS_ROUTER_TRANSITION_START_EXPORT = "__vinextHasRouterTransitionStart"; | ||
|
|
||
| /** Logged when one instrumentation-client module's router transition hook throws. */ | ||
| export const INSTRUMENTATION_CLIENT_HOOK_FAILED_MESSAGE = | ||
| "An instrumentation-client router transition hook failed"; | ||
|
|
||
| export type RouterTransitionType = "push" | "replace" | "traverse"; | ||
|
|
||
| /** How the `<Link>` that started a navigation prefetches: `prefetch={true}` is "full". */ | ||
| export type RouterTransitionPrefetchIntent = "full" | "auto" | "none"; | ||
|
|
||
| /** Next.js' `RouterTransitionStartEvent` (client/router-transition-types.ts). */ | ||
| export type RouterTransitionStartEvent = { | ||
| id: string; | ||
| timestamp: number; | ||
| /** Source route patterns of the page being left, its primary route first. */ | ||
| fromRoutes: string[]; | ||
| /** `null` when the navigation did not start from a `<Link>`. */ | ||
| prefetchIntent: RouterTransitionPrefetchIntent | null; | ||
| }; | ||
|
|
||
| // The App Router browser entry registers how to read the committed route tree. | ||
| // It lives on globalThis for the same reason as the hooks above. | ||
| const VINEXT_ROUTER_TRANSITION_FROM_ROUTES = Symbol.for("vinext.client.routerTransitionFromRoutes"); | ||
|
|
||
| export function setRouterTransitionFromRoutesResolver(resolve: (() => string[]) | null): void { | ||
| Reflect.set(globalThis, VINEXT_ROUTER_TRANSITION_FROM_ROUTES, resolve); | ||
| } | ||
|
|
||
| function resolveRouterTransitionFromRoutes(): string[] { | ||
| const resolve = Reflect.get(globalThis, VINEXT_ROUTER_TRANSITION_FROM_ROUTES) as | ||
| | (() => string[]) | ||
| | null | ||
| | undefined; | ||
| return resolve ? resolve() : []; | ||
| } | ||
|
|
||
| let nextTransitionId = 0; | ||
|
|
||
| /** | ||
| * Mirrors Next.js' `startRouterTransition` without | ||
| * `experimental.instrumentationClientRouterTransitionEvents`: the third | ||
| * argument is `null`, and a throwing hook is logged instead of breaking the | ||
| * navigation (client/components/router-transition.ts). | ||
| * Mirrors Next.js' `startRouterTransition` | ||
| * (client/components/router-transition.ts). The third argument is `null` | ||
| * unless `experimental.instrumentationClientRouterTransitionEvents` is set, | ||
| * and a throwing hook is logged instead of breaking the navigation. | ||
| */ | ||
| export function notifyAppRouterTransitionStart( | ||
| href: string, | ||
| navigationType: "push" | "replace" | "traverse", | ||
| navigationType: RouterTransitionType, | ||
| prefetchIntent: RouterTransitionPrefetchIntent | null = null, | ||
| ): void { | ||
| const hooks = getClientInstrumentationHooks(); | ||
| if (typeof hooks?.onRouterTransitionStart !== "function") return; | ||
| // Next.js numbers a transition only when some module has a hook. The | ||
| // inject fan-out is always a function, so it reports that itself. | ||
| if ( | ||
| process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS && | ||
| hooks[HAS_ROUTER_TRANSITION_START_EXPORT]?.() === false | ||
| ) { | ||
| return; | ||
| } | ||
| // Positive flag check so the event path drops out of builds without the flag. | ||
| const id = process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS | ||
| ? `${Date.now().toString(36)}-${(++nextTransitionId).toString(36)}` | ||
| : null; | ||
| try { | ||
| getClientInstrumentationHooks()?.onRouterTransitionStart?.(href, navigationType, null); | ||
| // Built inside the try like Next.js, so a failure is logged like a | ||
| // throwing hook. | ||
| const event: RouterTransitionStartEvent | null = | ||
| id === null | ||
| ? null | ||
| : { | ||
| id, | ||
| timestamp: performance.timeOrigin + performance.now(), | ||
| fromRoutes: resolveRouterTransitionFromRoutes(), | ||
| prefetchIntent, | ||
| }; | ||
| hooks.onRouterTransitionStart(href, navigationType, event); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. With
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 5e5007d: the generated fan-out now passes each hook its own copy of the event, with its own |
||
| } catch (error) { | ||
| console.error(INSTRUMENTATION_CLIENT_HOOK_FAILED_MESSAGE, error); | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -486,6 +486,12 @@ export type NextConfig = { | |
| * `useRouter().experimental_gesturePush()`. | ||
| */ | ||
| gestureTransition?: boolean; | ||
| /** | ||
| * Passes a start event (`id`, `timestamp`, `fromRoutes`, `prefetchIntent`) | ||
| * as the third argument of the instrumentation-client | ||
| * `onRouterTransitionStart` hook. Without it the hook receives `null`. | ||
| */ | ||
| instrumentationClientRouterTransitionEvents?: boolean; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The runtime type exported from |
||
| /** | ||
| * Enables App Router Segment Cache prefetch inlining. When provided as an | ||
| * object, thresholds are resolved with Next.js defaults and non-finite | ||
|
|
@@ -591,6 +597,8 @@ export type ResolvedNextConfig = { | |
| * `useRouter().experimental_gesturePush()`. | ||
| */ | ||
| gestureTransition: boolean; | ||
| /** `experimental.instrumentationClientRouterTransitionEvents`. */ | ||
| instrumentationClientRouterTransitionEvents: boolean; | ||
| /** | ||
| * Resolved `experimental.prefetchInlining` config. Next.js normalizes `true` | ||
| * and partial object config into concrete thresholds. | ||
|
|
@@ -2026,6 +2034,7 @@ export async function resolveNextConfig( | |
| cachedNavigations: false, | ||
| appNavFailHandling: false, | ||
| gestureTransition: false, | ||
| instrumentationClientRouterTransitionEvents: false, | ||
| prefetchInlining: false, | ||
| redirects: [], | ||
| rewrites: { beforeFiles: [], afterFiles: [], fallback: [] }, | ||
|
|
@@ -2471,6 +2480,8 @@ export async function resolveNextConfig( | |
| cachedNavigations: cacheComponents && experimental?.cachedNavigations === true, | ||
| appNavFailHandling: experimental?.appNavFailHandling === true, | ||
| gestureTransition: experimental?.gestureTransition === true, | ||
| instrumentationClientRouterTransitionEvents: | ||
| experimental?.instrumentationClientRouterTransitionEvents === true, | ||
| prefetchInlining, | ||
| redirects, | ||
| rewrites, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -20,7 +20,11 @@ import { flushSync } from "react-dom"; | |
| import { createRoot, hydrateRoot } from "react-dom/client"; | ||
| import "../client/instrumentation-client.js"; | ||
| import { AppRouterAnnouncer } from "../client/app-router-announcer.js"; | ||
| import { notifyAppRouterTransitionStart } from "../client/instrumentation-client-state.js"; | ||
| import { | ||
| notifyAppRouterTransitionStart, | ||
| setRouterTransitionFromRoutesResolver, | ||
| } from "../client/instrumentation-client-state.js"; | ||
| import { resolveRouterTransitionFromRoutes } from "./app-browser-transition-routes.js"; | ||
| import { | ||
| __basePath, | ||
| activateNavigationSnapshot, | ||
|
|
@@ -410,6 +414,16 @@ const browserNavigationController = createAppBrowserNavigationController({ | |
| syncHistoryStatePreviousNextUrl: (previousNextUrl, bfcacheIds) => | ||
| historyController.syncCurrentHistoryStatePreviousNextUrl(previousNextUrl, bfcacheIds), | ||
| }); | ||
|
|
||
| // experimental.instrumentationClientRouterTransitionEvents: report the source | ||
| // routes of the committed tree. The flag check drops the resolver otherwise. | ||
| if (process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS) { | ||
| setRouterTransitionFromRoutesResolver(() => | ||
| hasBrowserRouterState() | ||
| ? resolveRouterTransitionFromRoutes(getBrowserRouterState(), getBrowserRouteManifest()) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The resolver can run before the manifest exists.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in e4783fc: with
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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 The rest of this round's fix makes the remaining gap small. The primary route now comes from the committed payload's |
||
| : [], | ||
| ); | ||
| } | ||
| const discardedServerActionRefreshScheduler = hasServerActions | ||
| ? createDiscardedServerActionRefreshScheduler({ | ||
| runRefresh() { | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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 incrementingnextTransitionIdor resolvingfromRoutes. 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...-2instead of...-1. Give the aggregate a live has-hook probe or defer rich-event creation into its fan-out.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 3068c5e. The generated inject module now also exports
__vinextHasRouterTransitionStart(), a live check that reads each module's hook the same way the fan-out does. With the flag on,notifyAppRouterTransitionStartreturns before numbering the transition or resolvingfromRouteswhen that check reports no hook, as Next's.some(...)does. A read that throws counts as a hook, so the fan-out still logs it rather than the transition being skipped silently. With the flag off, the check isn't called and that path drops out, as before.New tests: "reports whether any module has a hook right now" covers a late CommonJS getter and a throwing read. "skips a transition while the inject fan-out has no hook to call" checks that a skipped transition takes no id and never runs the resolver. Both fail on the previous head. The dev e2e still passes.