Unverified Commit 34759c3e authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

router instrumentation: add transition start context (2/7) (#94766)

## Stack Position

(2/7) in the router instrumentation stack.

1. #94755: router instrumentation: refactor client hook dispatch (1/7)
2. **#94766: router instrumentation: add transition start context
(2/7)**
3. #94756: router instrumentation: add transition commit events (3/7)
4. #94765: router instrumentation: add commit route and prefetch context
(4/7)
5. #94757: router instrumentation: add transition abort events (5/7)
6. #94758: router instrumentation: add route mismatch events (6/7)
7. #94737: router instrumentation: add transition settlement events
(7/7)

Parent: #94755
Next: #94756

## What This PR Does

Adds an experimental third argument to the existing start hook:

```ts
export function onRouterTransitionStart(url, navigationType, event) {}
```

The event contains:

- `id` and framework-captured Unix `timestamp` in milliseconds
- `fromRoutes`: route patterns visible when navigation is dispatched
- `prefetchIntent`: `full`, `auto`, or `none`

The primary `children` route is first, followed by visible parallel
slots in deterministic order.

## Design

Start owns the context that is authoritative before navigation work
begins: the screen being left and the caller's prefetch intent.
Destination routes and the cache result actually used are reported by
commit instead. Consumers correlate them by transition ID.

Without `experimental.instrumentationClientRouterTransitionEvents`, the
existing two-argument hook behavior is unchanged.

## Not In This PR

- Destination routes or observed prefetch result
- Commit, abort, mismatch, or settled hooks

## Reviewer Focus

- Route pattern extraction, including dynamic and parallel routes
- Primary route ordering
- Link intent propagation and experimental gating

## Validation

- `pnpm build-all`
- `pnpm --filter=next build`
- App Router instrumentation client E2E: 15/15

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarJude Gao <jude.gao@vercel.com>
parent 47d4abc1
...@@ -43,33 +43,70 @@ window.addEventListener('error', (event) => { ...@@ -43,33 +43,70 @@ window.addEventListener('error', (event) => {
## Router navigation tracking ## Router navigation tracking
You can export an `onRouterTransitionStart` function to receive notifications when navigation begins: You can export `onRouterTransitionStart` to observe the start of App Router navigations:
```ts filename="instrumentation-client.ts"
export function onRouterTransitionStart(
url: string,
navigationType: 'push' | 'replace' | 'traverse'
) {
console.log(url, navigationType)
}
```
Additional router transition information is experimental. Enable it to receive a third `event` argument:
```ts filename="next.config.ts"
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
instrumentationClientRouterTransitionEvents: true,
},
}
export default nextConfig
```
The event includes the transition metadata and source context known when the navigation is dispatched:
```ts filename="instrumentation-client.ts" switcher ```ts filename="instrumentation-client.ts" switcher
performance.mark('app-init') import type { RouterTransitionStartEvent, RouterTransitionType } from 'next'
export function onRouterTransitionStart( export function onRouterTransitionStart(
url: string, url: string,
navigationType: 'push' | 'replace' | 'traverse' navigationType: RouterTransitionType,
{ id, timestamp, fromRoutes, prefetchIntent }: RouterTransitionStartEvent
) { ) {
console.log(`Navigation started: ${navigationType} to ${url}`) console.log(id, timestamp, url, navigationType, fromRoutes, prefetchIntent)
performance.mark(`nav-start-${Date.now()}`)
} }
``` ```
```js filename="instrumentation-client.js" switcher ```js filename="instrumentation-client.js" switcher
performance.mark('app-init') export function onRouterTransitionStart(url, navigationType, event) {
console.log(
export function onRouterTransitionStart(url, navigationType) { event.id,
console.log(`Navigation started: ${navigationType} to ${url}`) event.timestamp,
performance.mark(`nav-start-${Date.now()}`) url,
navigationType,
event.fromRoutes,
event.prefetchIntent
)
} }
``` ```
The `onRouterTransitionStart` function receives two parameters: `onRouterTransitionStart` receives:
- `url: string` - The URL being navigated to - `url: string` - The URL being navigated to
- `navigationType: 'push' | 'replace' | 'traverse'` - The type of navigation - `navigationType: 'push' | 'replace' | 'traverse'` - The type of navigation
- `event.id` - An opaque ID shared by events for this transition
- `event.timestamp` - A framework-captured Unix timestamp in milliseconds
- `event.fromRoutes` - Route patterns visible before navigation. The primary `children` route is first, followed by parallel slots in deterministic order
- `event.prefetchIntent` - For link navigations, whether the clicked link requested full prefetching (`full`), used automatic prefetching (`auto`), or did not request prefetching (`none`). For navigations with no associated link (programmatic `router.push()`/`router.replace()`, or browser back/forward) this is `null`, since no link prefetch intent applies
Route entries use filesystem-style patterns, so a navigation away from `/blog/hello` may report `/blog/[slug]`.
Hook errors are isolated and do not affect navigation or other hooks.
## Performance considerations ## Performance considerations
...@@ -89,7 +126,7 @@ This timing makes it ideal for setting up error tracking, analytics, and perform ...@@ -89,7 +126,7 @@ This timing makes it ideal for setting up error tracking, analytics, and perform
## See also ## See also
`next.config.js` plugins (for example, wrappers like `withSentry`) can register their own client instrumentation module via the [`instrumentationClientInject`](/docs/app/api-reference/config/next-config-js/instrumentationClientInject) option. Injected modules run before this file, in array order, and may export their own `onRouterTransitionStart`. Application code should continue to use this file convention directly. `next.config.js` plugins (for example, wrappers like `withSentry`) can register their own client instrumentation module via the [`instrumentationClientInject`](/docs/app/api-reference/config/next-config-js/instrumentationClientInject) option. Injected modules run before this file, in array order, and may export the same router transition start hook. Application code should continue to use this file convention directly.
## Examples ## Examples
...@@ -224,5 +261,6 @@ if (!window.ResizeObserver) { ...@@ -224,5 +261,6 @@ if (!window.ResizeObserver) {
## Version history ## Version history
| Version | Changes | | Version | Changes |
| ------- | ----------------------------------- | | --------- | ----------------------------------------------------- |
| `v16.3.0` | Experimental router transition start event introduced |
| `v15.3` | `instrumentation-client` introduced | | `v15.3` | `instrumentation-client` introduced |
...@@ -378,6 +378,8 @@ export function getDefineEnv({ ...@@ -378,6 +378,8 @@ export function getDefineEnv({
config.experimental.gestureTransition ?? false, config.experimental.gestureTransition ?? false,
'process.env.__NEXT_OPTIMISTIC_ROUTING': 'process.env.__NEXT_OPTIMISTIC_ROUTING':
config.experimental.optimisticRouting ?? false, config.experimental.optimisticRouting ?? false,
'process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS':
config.experimental.instrumentationClientRouterTransitionEvents ?? false,
'process.env.__NEXT_APP_SHELLS': config.experimental.appShells ?? false, 'process.env.__NEXT_APP_SHELLS': config.experimental.appShells ?? false,
'process.env.__NEXT_VARY_PARAMS': config.experimental.varyParams ?? false, 'process.env.__NEXT_VARY_PARAMS': config.experimental.varyParams ?? false,
'process.env.__NEXT_EXPOSE_TESTING_API': 'process.env.__NEXT_EXPOSE_TESTING_API':
......
...@@ -22,6 +22,7 @@ import { ...@@ -22,6 +22,7 @@ import {
FetchStrategy, FetchStrategy,
type PrefetchTaskFetchStrategy, type PrefetchTaskFetchStrategy,
} from '../components/segment-cache/types' } from '../components/segment-cache/types'
import type { RouterTransitionPrefetchIntent } from '../router-transition-types'
type Url = string | UrlObject type Url = string | UrlObject
type RequiredKeys<T> = { type RequiredKeys<T> = {
...@@ -256,7 +257,8 @@ function linkClicked( ...@@ -256,7 +257,8 @@ function linkClicked(
replace?: boolean, replace?: boolean,
scroll?: boolean, scroll?: boolean,
onNavigate?: OnNavigateEventHandler, onNavigate?: OnNavigateEventHandler,
transitionTypes?: string[] transitionTypes?: string[],
prefetchIntent: RouterTransitionPrefetchIntent = 'none'
): void { ): void {
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
const { nodeName } = e.currentTarget const { nodeName } = e.currentTarget
...@@ -308,7 +310,8 @@ function linkClicked( ...@@ -308,7 +310,8 @@ function linkClicked(
replace ? 'replace' : 'push', replace ? 'replace' : 'push',
scroll === false ? ScrollBehavior.NoScroll : ScrollBehavior.Default, scroll === false ? ScrollBehavior.NoScroll : ScrollBehavior.Default,
linkInstanceRef.current, linkInstanceRef.current,
transitionTypes transitionTypes,
prefetchIntent
) )
}) })
} }
...@@ -376,10 +379,12 @@ export default function LinkComponent( ...@@ -376,10 +379,12 @@ export default function LinkComponent(
const router = React.useContext(AppRouterContext) const router = React.useContext(AppRouterContext)
const prefetchEnabled = prefetchProp !== false const prefetchEnabled = prefetchProp !== false
const prefetchIntent: RouterTransitionPrefetchIntent =
prefetchProp === false ? 'none' : prefetchProp === true ? 'full' : 'auto'
const fetchStrategy = const fetchStrategy =
prefetchProp !== false prefetchIntent !== 'none'
? getFetchStrategyFromPrefetchProp(prefetchProp) ? getFetchStrategyFromPrefetchIntent(prefetchIntent)
: // TODO: it makes no sense to assign a fetchStrategy when prefetching is disabled. : // TODO: it makes no sense to assign a fetchStrategy when prefetching is disabled.
FetchStrategy.PPR FetchStrategy.PPR
...@@ -692,7 +697,8 @@ export default function LinkComponent( ...@@ -692,7 +697,8 @@ export default function LinkComponent(
replace, replace,
scroll, scroll,
onNavigate, onNavigate,
transitionTypes transitionTypes,
prefetchIntent
) )
}, },
onMouseEnter(e) { onMouseEnter(e) {
...@@ -799,26 +805,23 @@ export const useLinkStatus = () => { ...@@ -799,26 +805,23 @@ export const useLinkStatus = () => {
return useContext(LinkStatusContext) return useContext(LinkStatusContext)
} }
function getFetchStrategyFromPrefetchProp( function getFetchStrategyFromPrefetchIntent(
prefetchProp: Exclude<LinkProps['prefetch'], undefined | false> prefetchIntent: Exclude<RouterTransitionPrefetchIntent, 'none'>
): PrefetchTaskFetchStrategy { ): PrefetchTaskFetchStrategy {
if (process.env.__NEXT_CACHE_COMPONENTS) { if (process.env.__NEXT_CACHE_COMPONENTS) {
if (prefetchProp === true) { if (prefetchIntent === 'full') {
return FetchStrategy.Full return FetchStrategy.Full
} }
// `null` or `"auto"`: this is the default "auto" mode, where we will prefetch partially if the link is in the viewport. // `"auto"`: the default mode, where we will prefetch partially if the link is in the viewport.
// This will also include invalid prop values that don't match the types specified here. prefetchIntent satisfies 'auto'
// (although those should've been filtered out by prop validation in dev)
prefetchProp satisfies null | 'auto'
return FetchStrategy.PPR return FetchStrategy.PPR
} else { } else {
return prefetchProp === null || prefetchProp === 'auto' return prefetchIntent === 'auto'
? // We default to PPR, and we'll discover whether or not the route supports it with the initial prefetch. ? // We default to PPR, and we'll discover whether or not the route supports it with the initial prefetch.
FetchStrategy.PPR FetchStrategy.PPR
: // In the old implementation without runtime prefetches, `prefetch={true}` forces all dynamic data to be prefetched. : // In the old implementation without runtime prefetches, `prefetch={true}` (`'full'`) forces all dynamic
// To preserve backwards-compatibility, anything other than `false`, `null`, or `"auto"` results in a full prefetch. // data to be prefetched, preserving backwards-compatibility.
// (although invalid values should've been filtered out by prop validation in dev)
FetchStrategy.Full FetchStrategy.Full
} }
} }
...@@ -35,6 +35,7 @@ import type { ...@@ -35,6 +35,7 @@ import type {
PrefetchOptions, PrefetchOptions,
} from '../../shared/lib/app-router-context.shared-runtime' } from '../../shared/lib/app-router-context.shared-runtime'
import { setLinkForCurrentNavigation, type LinkInstance } from './links' import { setLinkForCurrentNavigation, type LinkInstance } from './links'
import type { RouterTransitionPrefetchIntent } from '../router-transition-types'
import type { GlobalErrorComponent } from './builtin/global-error' import type { GlobalErrorComponent } from './builtin/global-error'
import { isJavaScriptURLString } from '../lib/javascript-url' import { isJavaScriptURLString } from '../lib/javascript-url'
import { startRouterTransition } from './router-transition' import { startRouterTransition } from './router-transition'
...@@ -262,7 +263,8 @@ export function dispatchNavigateAction( ...@@ -262,7 +263,8 @@ export function dispatchNavigateAction(
navigateType: NavigateAction['navigateType'], navigateType: NavigateAction['navigateType'],
scrollBehavior: ScrollBehavior, scrollBehavior: ScrollBehavior,
linkInstanceRef: LinkInstance | null, linkInstanceRef: LinkInstance | null,
transitionTypes: string[] | undefined transitionTypes: string[] | undefined,
prefetchIntent: RouterTransitionPrefetchIntent | null
): void { ): void {
// TODO: This stuff could just go into the reducer. Leaving as-is for now // TODO: This stuff could just go into the reducer. Leaving as-is for now
// since we're about to rewrite all the router reducer stuff anyway. // since we're about to rewrite all the router reducer stuff anyway.
...@@ -279,7 +281,12 @@ export function dispatchNavigateAction( ...@@ -279,7 +281,12 @@ export function dispatchNavigateAction(
} }
setLinkForCurrentNavigation(linkInstanceRef) setLinkForCurrentNavigation(linkInstanceRef)
startRouterTransition(href, navigateType) startRouterTransition(
href,
navigateType,
getAppRouterActionQueue().state.tree,
prefetchIntent
)
dispatchAppRouterAction({ dispatchAppRouterAction({
type: ACTION_NAVIGATE, type: ACTION_NAVIGATE,
...@@ -295,7 +302,12 @@ export function dispatchTraverseAction( ...@@ -295,7 +302,12 @@ export function dispatchTraverseAction(
href: string, href: string,
historyState: AppHistoryState | undefined historyState: AppHistoryState | undefined
) { ) {
startRouterTransition(href, 'traverse') startRouterTransition(
href,
'traverse',
getAppRouterActionQueue().state.tree,
null
)
dispatchAppRouterAction({ dispatchAppRouterAction({
type: ACTION_RESTORE, type: ACTION_RESTORE,
url: new URL(href), url: new URL(href),
...@@ -425,7 +437,8 @@ export const publicAppRouterInstance: AppRouterInstance = { ...@@ -425,7 +437,8 @@ export const publicAppRouterInstance: AppRouterInstance = {
? ScrollBehavior.NoScroll ? ScrollBehavior.NoScroll
: ScrollBehavior.Default, : ScrollBehavior.Default,
null, null,
options?.transitionTypes options?.transitionTypes,
null
) )
}) })
}, },
...@@ -443,7 +456,8 @@ export const publicAppRouterInstance: AppRouterInstance = { ...@@ -443,7 +456,8 @@ export const publicAppRouterInstance: AppRouterInstance = {
? ScrollBehavior.NoScroll ? ScrollBehavior.NoScroll
: ScrollBehavior.Default, : ScrollBehavior.Default,
null, null,
options?.transitionTypes options?.transitionTypes,
null
) )
}) })
}, },
......
import { computeChangedPath } from './compute-changed-path' import {
import { PrefetchHint } from '../../../shared/lib/app-router-types' computeChangedPath,
segmentToSourcePagePathname,
} from './compute-changed-path'
import {
type Segment,
PrefetchHint,
} from '../../../shared/lib/app-router-types'
describe('computeChangedPath', () => { describe('computeChangedPath', () => {
const sourceRouteSegmentCases: Array<[Segment, string]> = [
[['slug', 'hello', 'd', null], '[slug]'],
[['slug', 'hello', 'c', null], '[...slug]'],
[['slug', 'hello', 'oc', null], '[[...slug]]'],
[['slug', 'hello', 'di(.)', null], '(.)[slug]'],
[['slug', 'hello', 'di(..)', null], '(..)[slug]'],
[['slug', 'hello', 'di(..)(..)', null], '(..)(..)[slug]'],
[['slug', 'hello', 'di(...)', null], '(...)[slug]'],
[['slug', 'hello', 'ci(.)', null], '(.)[...slug]'],
[['slug', 'hello', 'ci(..)', null], '(..)[...slug]'],
[['slug', 'hello', 'ci(..)(..)', null], '(..)(..)[...slug]'],
[['slug', 'hello', 'ci(...)', null], '(...)[...slug]'],
]
it.each(sourceRouteSegmentCases)(
'formats source route segment %j as %s',
(segment, expected) => {
expect(segmentToSourcePagePathname(segment)).toBe(expected)
}
)
it('should return the correct path', () => { it('should return the correct path', () => {
expect( expect(
computeChangedPath( computeChangedPath(
......
...@@ -27,7 +27,7 @@ const segmentToPathname = (segment: Segment): string => { ...@@ -27,7 +27,7 @@ const segmentToPathname = (segment: Segment): string => {
return segment[1] return segment[1]
} }
const segmentToSourcePagePathname = (segment: Segment): string => { export const segmentToSourcePagePathname = (segment: Segment): string => {
if (typeof segment === 'string') { if (typeof segment === 'string') {
if (segment === 'children') return '' if (segment === 'children') return ''
if (segment.startsWith(PAGE_SEGMENT_KEY)) return 'page' if (segment.startsWith(PAGE_SEGMENT_KEY)) return 'page'
......
import type {
FlightRouterState,
Segment,
} from '../../shared/lib/app-router-types'
import {
DEFAULT_SEGMENT_KEY,
isGroupSegment,
NOT_FOUND_SEGMENT_KEY,
} from '../../shared/lib/segment'
import { segmentToSourcePagePathname } from './router-reducer/compute-changed-path'
import type { import type {
ClientInstrumentationHooks, ClientInstrumentationHooks,
ClientInstrumentationModules, ClientInstrumentationModules,
RouterTransitionPrefetchIntent,
RouterTransitionType, RouterTransitionType,
} from '../router-transition-types' } from '../router-transition-types'
let instrumentationModules: readonly ClientInstrumentationHooks[] = [] let instrumentationModules: readonly ClientInstrumentationHooks[] = []
let nextTransitionId = 0
export function initializeRouterTransitionModules( export function initializeRouterTransitionModules(
modules: ClientInstrumentationModules modules: ClientInstrumentationModules
...@@ -27,9 +39,106 @@ function callHooks(invoke: (hooks: ClientInstrumentationHooks) => void): void { ...@@ -27,9 +39,106 @@ function callHooks(invoke: (hooks: ClientInstrumentationHooks) => void): void {
} }
} }
function timestamp(): number {
return performance.timeOrigin + performance.now()
}
export function startRouterTransition( export function startRouterTransition(
url: string, url: string,
type: RouterTransitionType type: RouterTransitionType,
fromTree: FlightRouterState,
prefetchIntent: RouterTransitionPrefetchIntent | null
): void { ): void {
callHooks((hooks) => hooks.onRouterTransitionStart?.(url, type)) // Positive flag check so the instrumentation-only path is removed by DCE when disabled.
if (process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS) {
if (
!instrumentationModules.some(
(hooks) => typeof hooks.onRouterTransitionStart === 'function'
)
) {
return
}
const id = `${Date.now().toString(36)}-${(++nextTransitionId).toString(36)}`
callHooks((hooks) =>
hooks.onRouterTransitionStart?.(url, type, {
id,
timestamp: timestamp(),
fromRoutes: getActiveRoutePaths(fromTree),
prefetchIntent,
})
)
} else {
callHooks((hooks) => hooks.onRouterTransitionStart?.(url, type, null))
}
}
function classifySegment(segment: Segment): {
path: string | null
isPage: boolean
} {
const sourceSegment = segmentToSourcePagePathname(segment)
if (sourceSegment === 'page') {
return { path: null, isPage: true }
}
if (
sourceSegment === '' ||
sourceSegment === '(__SLOT__)' ||
isGroupSegment(sourceSegment)
) {
return { path: null, isPage: false }
}
if (sourceSegment === DEFAULT_SEGMENT_KEY) {
return { path: 'default', isPage: false }
}
if (sourceSegment === NOT_FOUND_SEGMENT_KEY) {
return { path: '_not-found', isPage: false }
}
return { path: sourceSegment, isPage: false }
}
function getActiveRoutePaths(tree: FlightRouterState): string[] {
const routes: Array<{ path: string; primary: boolean }> = []
function visit(
node: FlightRouterState,
segments: string[],
primary: boolean
): void {
const segment = classifySegment(node[0])
const nextSegments =
segment.path === null ? segments : [...segments, segment.path]
const parallelRoutes = node[1]
const keys = Object.keys(parallelRoutes)
if (keys.length === 0 || segment.isPage) {
routes.push({
path: `/${nextSegments.join('/')}`,
primary,
})
return
}
if (parallelRoutes.children !== undefined) {
visit(parallelRoutes.children, nextSegments, primary)
}
for (const key of keys.sort()) {
if (key === 'children') {
continue
}
visit(parallelRoutes[key], [...nextSegments, `@${key}`], false)
}
}
visit(tree, [], true)
return routes
.sort((a, b) => {
if (a.primary !== b.primary) {
return a.primary ? -1 : 1
}
return a.path.localeCompare(b.path)
})
.map((route) => route.path)
} }
export type RouterTransitionType = 'push' | 'replace' | 'traverse' export type RouterTransitionType = 'push' | 'replace' | 'traverse'
export type RouterTransitionPrefetchIntent = 'full' | 'auto' | 'none'
export type RouterTransitionEvent = {
id: string
timestamp: number
}
export type RouterTransitionStartEvent = RouterTransitionEvent & {
fromRoutes: string[]
// `null` for non-prefetch transitions.
prefetchIntent: RouterTransitionPrefetchIntent | null
}
export type ClientInstrumentationHooks = { export type ClientInstrumentationHooks = {
onRouterTransitionStart?: ( onRouterTransitionStart?: (
url: string, url: string,
navigationType: RouterTransitionType navigationType: RouterTransitionType,
event: RouterTransitionStartEvent | null
) => void ) => void
} }
......
...@@ -224,6 +224,7 @@ export const experimentalSchema = { ...@@ -224,6 +224,7 @@ export const experimentalSchema = {
dynamicOnHover: z.boolean().optional(), dynamicOnHover: z.boolean().optional(),
useOffline: z.boolean().optional(), useOffline: z.boolean().optional(),
optimisticRouting: z.boolean().optional(), optimisticRouting: z.boolean().optional(),
instrumentationClientRouterTransitionEvents: z.boolean().optional(),
appShells: z.boolean().optional(), appShells: z.boolean().optional(),
varyParams: z.boolean().optional(), varyParams: z.boolean().optional(),
prefetchInlining: z prefetchInlining: z
......
...@@ -477,6 +477,7 @@ export interface ExperimentalConfig { ...@@ -477,6 +477,7 @@ export interface ExperimentalConfig {
dynamicOnHover?: boolean dynamicOnHover?: boolean
useOffline?: boolean useOffline?: boolean
optimisticRouting?: boolean optimisticRouting?: boolean
instrumentationClientRouterTransitionEvents?: boolean
/** /**
* Enables App Shell prefetching: a route's reusable, param-free loading * Enables App Shell prefetching: a route's reusable, param-free loading
* state is prefetched once per session and served instantly for any * state is prefetched once per session and served instantly for any
...@@ -2025,6 +2026,7 @@ export const defaultConfig = Object.freeze({ ...@@ -2025,6 +2026,7 @@ export const defaultConfig = Object.freeze({
useOffline: false, useOffline: false,
varyParams: true, varyParams: true,
optimisticRouting: true, optimisticRouting: true,
instrumentationClientRouterTransitionEvents: false,
prefetchInlining: true, prefetchInlining: true,
preloadEntriesOnStart: true, preloadEntriesOnStart: true,
clientRouterFilter: true, clientRouterFilter: true,
......
...@@ -43,6 +43,12 @@ export type { ...@@ -43,6 +43,12 @@ export type {
export type { Instant } from './build/segment-config/app/app-segment-config' export type { Instant } from './build/segment-config/app/app-segment-config'
export type { Instrumentation } from './server/instrumentation/types' export type { Instrumentation } from './server/instrumentation/types'
export type {
RouterTransitionType,
RouterTransitionPrefetchIntent,
RouterTransitionEvent,
RouterTransitionStartEvent,
} from './client/router-transition-types'
/** /**
* Stub route type for typedRoutes before `next dev` or `next build` is run * Stub route type for typedRoutes before `next dev` or `next build` is run
......
export default function Page() {
return <h1 id="about">About</h1>
}
export default function Page() {
return <h1 id="blog-post">Blog post</h1>
}
export default function Page() {
return <p id="analytics">Analytics</p>
}
export default function DashboardLayout({
children,
analytics,
}: {
children: React.ReactNode
analytics: React.ReactNode
}) {
return (
<>
{children}
{analytics}
</>
)
}
export default function Page() {
return <h1 id="dashboard">Dashboard</h1>
}
export default function Page() {
return <h1 id="photo-modal">Photo modal</h1>
}
import React from 'react'
export default function GalleryLayout({
children,
modal,
}: {
children: React.ReactNode
modal: React.ReactNode
}) {
return (
<>
{children}
{modal}
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<div>
<h1 id="gallery">Gallery</h1>
<Link href="/gallery/photos/1">Photo 1</Link>
</div>
)
}
export default function Page() {
return <h1 id="photo">Photo</h1>
}
...@@ -9,7 +9,15 @@ export default function RootLayout({ children }) { ...@@ -9,7 +9,15 @@ export default function RootLayout({ children }) {
<Link href="/">Home</Link> <Link href="/">Home</Link>
</li> </li>
<li> <li>
<Link href="/some-page">Some Page</Link> <Link href="/some-page" prefetch={true}>
Some Page
</Link>
</li>
<li>
<Link href="/dashboard">Dashboard</Link>
</li>
<li>
<Link href="/blog/hello">Blog post</Link>
</li> </li>
</ul> </ul>
{children} {children}
......
import { PushButton } from './push-button'
export default function Page() { export default function Page() {
return <h1 id="home">Home</h1> return (
<>
<h1 id="home">Home</h1>
<PushButton />
</>
)
} }
'use client'
import { useRouter } from 'next/navigation'
export function PushButton() {
const router = useRouter()
return (
<button id="push-some-page" onClick={() => router.push('/some-page')}>
Push some page
</button>
)
}
;(window as any).__INSTRUMENTATION_CLIENT_EXECUTED_AT = performance.now() ;(window as any).__INSTRUMENTATION_CLIENT_EXECUTED_AT = performance.now()
;(window as any).__ROUTER_TRANSITION_EVENTS = []
const start = performance.now() const start = performance.now()
while (performance.now() - start < 20) { while (performance.now() - start < 20) {
// Intentionally block for 20ms to test instrumentation timing // Intentionally block for 20ms to test instrumentation timing
} }
export function onRouterTransitionStart(href: string, navigateType: string) { function record(
phase: string,
href: string,
navigateType: string,
event: unknown
) {
;(window as any).__ROUTER_TRANSITION_EVENTS.push({
phase,
url: new URL(href, window.location.href).pathname,
navigateType,
event,
})
}
export function onRouterTransitionStart(
href: string,
navigateType: string,
event: unknown
) {
const pathname = new URL(href, window.location.href).pathname const pathname = new URL(href, window.location.href).pathname
console.log(`[Router Transition Start] [${navigateType}] ${pathname}`) console.log(`[Router Transition Start] [${navigateType}] ${pathname}`)
record('start', href, navigateType, event)
} }
...@@ -98,6 +98,114 @@ describe('Instrumentation Client Hook', () => { ...@@ -98,6 +98,114 @@ describe('Instrumentation Client Hook', () => {
'[Router Transition Start] [traverse] /some-page', '[Router Transition Start] [traverse] /some-page',
]) ])
}) })
it('preserves the legacy two-argument start hook without the experimental flag', async () => {
const browser = await next.browser('/')
await browser.elementByCss('a[href="/some-page"]').click()
await browser.elementById('some-page')
expect(
await browser.eval(`
window.__ROUTER_TRANSITION_EVENTS.map((event) => ({
phase: event.phase,
hasEvent: event.event != null,
}))
`)
).toEqual([{ phase: 'start', hasEvent: false }])
})
})
describe('router transition start context', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, 'app-router'),
nextConfig: {
experimental: {
instrumentationClientRouterTransitionEvents: true,
},
},
})
async function getTransitionEvents(browser) {
return browser.eval(`window.__ROUTER_TRANSITION_EVENTS`)
}
it('reports transition metadata, source routes, and prefetch intent', async () => {
const browser = await next.browser('/')
await browser.elementByCss('a[href="/some-page"]').click()
await browser.elementById('some-page')
const [start] = await getTransitionEvents(browser)
expect(start.phase).toBe('start')
expect(start.url).toBe('/some-page')
expect(start.navigateType).toBe('push')
expect(typeof start.event.id).toBe('string')
expect(start.event.timestamp).toBeGreaterThan(0)
expect(start.event.fromRoutes).toEqual(['/'])
expect(start.event.prefetchIntent).toBe('full')
})
it('reports a null prefetch intent for programmatic navigation', async () => {
const browser = await next.browser('/')
await browser.elementById('push-some-page').click()
await browser.elementById('some-page')
const [start] = await getTransitionEvents(browser)
expect(start.phase).toBe('start')
expect(start.url).toBe('/some-page')
expect(start.navigateType).toBe('push')
expect(start.event.prefetchIntent).toBe(null)
})
it('uses route patterns and puts the primary source route first', async () => {
const browser = await next.browser('/')
await browser.elementByCss('a[href="/blog/hello"]').click()
await browser.elementById('blog-post')
await browser.elementByCss('a[href="/"]').click()
await browser.elementById('home')
expect(
(await getTransitionEvents(browser)).at(-1).event.fromRoutes
).toEqual(['/blog/[slug]'])
await browser.elementByCss('a[href="/dashboard"]').click()
await browser.elementById('dashboard')
await browser.elementById('analytics')
await browser.elementByCss('a[href="/"]').click()
await browser.elementById('home')
expect(
(await getTransitionEvents(browser)).at(-1).event.fromRoutes
).toEqual(['/dashboard', '/dashboard/@analytics'])
})
it('omits route groups from fromRoutes', async () => {
const browser = await next.browser('/about')
await browser.elementByCss('a[href="/"]').click()
await browser.elementById('home')
expect(
(await getTransitionEvents(browser)).at(-1).event.fromRoutes
).toEqual(['/about'])
})
it('reports intercepted route patterns in fromRoutes', async () => {
const browser = await next.browser('/gallery')
await browser.elementByCss('a[href="/gallery/photos/1"]').click()
await browser.elementById('photo-modal')
await browser.elementByCss('a[href="/"]').click()
await browser.elementById('home')
expect(
(await getTransitionEvents(browser)).at(-1).event.fromRoutes
).toEqual(['/gallery', '/gallery/@modal/(.)photos/[id]'])
})
}) })
describe.each([ describe.each([
......
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <h1 id="other">Other</h1>
}
import Link from 'next/link'
export default function Page() {
return (
<div>
<h1 id="home">Home</h1>
<Link href="/other">Other</Link>
</div>
)
}
import { nextTestSetup } from 'e2e-utils'
// The router transition instrumentation only emits the rich transition event
// (which carries `fromRoutes`) when the experimental flag is enabled. That code
// path is gated behind `process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS`,
// which is replaced with a literal at build time so the disabled path can be
// dead-code-eliminated. `fromRoutes` is the marker: in client runtime code it
// appears only inside that gated branch, and object keys survive minification.
describe('instrumentation client router transition events - dead code elimination', () => {
describe('when the experimental flag is enabled', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
nextConfig: {
experimental: { instrumentationClientRouterTransitionEvents: true },
},
})
if (skipped) return
it('keeps the transition event payload in the client bundle', async () => {
const $ = await next.render$('/')
const chunkContents = await Promise.all(
$('script[src]')
.toArray()
.map((el) => next.fetch($(el).attr('src')).then((res) => res.text()))
)
expect(
chunkContents.some((content) => content.includes('fromRoutes'))
).toBe(true)
})
})
describe('when the experimental flag is disabled', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
})
if (skipped) return
it('removes the transition event payload from the client bundle', async () => {
const $ = await next.render$('/')
const chunkContents = await Promise.all(
$('script[src]')
.toArray()
.map((el) => next.fetch($(el).attr('src')).then((res) => res.text()))
)
expect(
chunkContents.some((content) => content.includes('fromRoutes'))
).toBe(false)
})
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment