Unverified Commit 6acd29d6 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Client instrumentation: onRouterTransitionStart (#77791)

Adds a new API for observing the start of an App Router navigation:

```ts
// <PROJECT_ROOT>/instrumentation-client.ts

export function onRouterTransitionStart(
  url: string,
  navigationType: 'push' | 'replace' | 'traverse'
) {
  // ...
}
```

`navigationType` is one of "push", "replace", or "traverse". This is
inspired by the Navigation API:

https://developer.mozilla.org/en-US/docs/Web/API/NavigateEvent/navigationType

`onRouterTransitionStart` is intended for sending logs to a performance
monitoring tool. It is _not_ intended as a general purpose event for
implementing application behavior.

It fires at the start of every client-side navigation, including those
initiated by a popstate (back/forward) event.

There is no corresponding API for observing the end of a navigation. We
intend to build support for this in the future, but it's a non-trivial
problem space due of the streaming nature of React transitions. Refer to
the React Transition Tracing proposal for more details:
https://github.com/reactjs/rfcs/blob/transition-tracing/text/0235-transition-tracing.md

`onRouterTransitionStart` is only called during App Router navigations.
To instrument Pages Router navigations, use `router.events`.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent d682610d
......@@ -159,41 +159,11 @@ const initialServerResponse = createFromReadableStream<InitialRSCPayload>(
{ callServer, findSourceMapURL }
)
// React overrides `.then` and doesn't return a new promise chain,
// so we wrap the action queue in a promise to ensure that its value
// is defined when the promise resolves.
// https://github.com/facebook/react/blob/163365a07872337e04826c4f501565d43dbd2fd4/packages/react-client/src/ReactFlightClient.js#L189-L190
const pendingActionQueue: Promise<AppRouterActionQueue> = new Promise(
(resolve, reject) => {
initialServerResponse.then(
(initialRSCPayload) => {
// setAppBuildId should be called only once, during JS initialization
// and before any components have hydrated.
setAppBuildId(initialRSCPayload.b)
const initialTimestamp = Date.now()
resolve(
createMutableActionQueue(
createInitialRouterState({
navigatedAt: initialTimestamp,
initialFlightData: initialRSCPayload.f,
initialCanonicalUrlParts: initialRSCPayload.c,
initialParallelRoutes: new Map(),
location: window.location,
couldBeIntercepted: initialRSCPayload.i,
postponed: initialRSCPayload.s,
prerendered: initialRSCPayload.S,
})
)
)
},
(err: Error) => reject(err)
)
}
)
function ServerRoot(): React.ReactNode {
function ServerRoot({
pendingActionQueue,
}: {
pendingActionQueue: Promise<AppRouterActionQueue>
}): React.ReactNode {
const initialRSCPayload = use(initialServerResponse)
const actionQueue = use<AppRouterActionQueue>(pendingActionQueue)
......@@ -241,12 +211,56 @@ const reactRootOptions: ReactDOMClient.RootOptions = {
onUncaughtError,
}
export function hydrate() {
export type ClientInstrumentationHooks = {
onRouterTransitionStart?: (
url: string,
navigationType: 'push' | 'replace' | 'traverse'
) => void
}
export function hydrate(
instrumentationHooks: ClientInstrumentationHooks | null
) {
// React overrides `.then` and doesn't return a new promise chain,
// so we wrap the action queue in a promise to ensure that its value
// is defined when the promise resolves.
// https://github.com/facebook/react/blob/163365a07872337e04826c4f501565d43dbd2fd4/packages/react-client/src/ReactFlightClient.js#L189-L190
const pendingActionQueue: Promise<AppRouterActionQueue> = new Promise(
(resolve, reject) => {
initialServerResponse.then(
(initialRSCPayload) => {
// setAppBuildId should be called only once, during JS initialization
// and before any components have hydrated.
setAppBuildId(initialRSCPayload.b)
const initialTimestamp = Date.now()
resolve(
createMutableActionQueue(
createInitialRouterState({
navigatedAt: initialTimestamp,
initialFlightData: initialRSCPayload.f,
initialCanonicalUrlParts: initialRSCPayload.c,
initialParallelRoutes: new Map(),
location: window.location,
couldBeIntercepted: initialRSCPayload.i,
postponed: initialRSCPayload.s,
prerendered: initialRSCPayload.S,
}),
instrumentationHooks
)
)
},
(err: Error) => reject(err)
)
}
)
const reactEl = (
<StrictModeIfEnabled>
<HeadManagerContext.Provider value={{ appDir: true }}>
<Root>
<ServerRoot />
<ServerRoot pendingActionQueue={pendingActionQueue} />
</Root>
</HeadManagerContext.Provider>
</StrictModeIfEnabled>
......
// TODO-APP: hydration warning
import './app-webpack'
import '../lib/require-instrumentation-client'
import { appBootstrap } from './app-bootstrap'
import { initializeDevBuildIndicatorForAppRouter } from './dev/dev-build-indicator/initialize-for-app-router'
const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap(() => {
const { hydrate } = require('./app-index')
hydrate()
hydrate(instrumentationHooks)
initializeDevBuildIndicatorForAppRouter()
})
// TODO-APP: hydration warning
import '../lib/require-instrumentation-client'
import { appBootstrap } from './app-bootstrap'
window.next.version += '-turbo'
;(self as any).__webpack_hash__ = ''
const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap(() => {
const { hydrate } = require('./app-index')
hydrate()
hydrate(instrumentationHooks)
if (process.env.NODE_ENV !== 'production') {
const { initializeDevBuildIndicatorForAppRouter } =
......
// This import must go first because it needs to patch webpack chunk loading
// before React patches chunk loading.
import './app-webpack'
import '../lib/require-instrumentation-client'
import { appBootstrap } from './app-bootstrap'
const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap(() => {
const { hydrate } = require('./app-index')
// Include app-router and layout-router in the main chunk
require('next/dist/client/components/app-router')
require('next/dist/client/components/layout-router')
hydrate()
hydrate(instrumentationHooks)
})
......@@ -25,6 +25,8 @@ import type {
PrefetchOptions,
} from '../../shared/lib/app-router-context.shared-runtime'
import { setLinkForCurrentNavigation, type LinkInstance } from './links'
import type { FlightRouterState } from '../../server/app-render/types'
import type { ClientInstrumentationHooks } from '../app-index'
export type DispatchStatePromise = React.Dispatch<ReducerState>
......@@ -32,6 +34,11 @@ export type AppRouterActionQueue = {
state: AppRouterState
dispatch: (payload: ReducerActions, setState: DispatchStatePromise) => void
action: (state: AppRouterState, action: ReducerActions) => ReducerState
onRouterTransitionStart:
| ((url: string, type: 'push' | 'replace' | 'traverse') => void)
| null
pending: ActionQueueNode | null
needsRefresh?: boolean
last: ActionQueueNode | null
......@@ -193,7 +200,8 @@ function dispatchAction(
let globalActionQueue: AppRouterActionQueue | null = null
export function createMutableActionQueue(
initialState: AppRouterState
initialState: AppRouterState,
instrumentationHooks: ClientInstrumentationHooks | null
): AppRouterActionQueue {
const actionQueue: AppRouterActionQueue = {
state: initialState,
......@@ -205,6 +213,12 @@ export function createMutableActionQueue(
},
pending: null,
last: null,
onRouterTransitionStart:
instrumentationHooks !== null &&
typeof instrumentationHooks.onRouterTransitionStart === 'function'
? // This profiling hook will be called at the start of every navigation.
instrumentationHooks.onRouterTransitionStart
: null,
}
if (typeof window !== 'undefined') {
......@@ -236,6 +250,13 @@ function getAppRouterActionQueue(): AppRouterActionQueue {
return globalActionQueue
}
function getProfilingHookForOnNavigationStart() {
if (globalActionQueue !== null) {
return globalActionQueue.onRouterTransitionStart
}
return null
}
export function dispatchNavigateAction(
href: string,
navigateType: NavigateAction['navigateType'],
......@@ -251,6 +272,11 @@ export function dispatchNavigateAction(
setLinkForCurrentNavigation(linkInstanceRef)
const onRouterTransitionStart = getProfilingHookForOnNavigationStart()
if (onRouterTransitionStart !== null) {
onRouterTransitionStart(href, navigateType)
}
dispatchAppRouterAction({
type: ACTION_NAVIGATE,
url,
......@@ -262,6 +288,21 @@ export function dispatchNavigateAction(
})
}
export function dispatchTraverseAction(
href: string,
tree: FlightRouterState | undefined
) {
const onRouterTransitionStart = getProfilingHookForOnNavigationStart()
if (onRouterTransitionStart !== null) {
onRouterTransitionStart(href, 'traverse')
}
dispatchAppRouterAction({
type: ACTION_RESTORE,
url: new URL(href),
tree,
})
}
/**
* The app router that is exposed through `useRouter`. These are public API
* methods. Internal Next.js code should call the lower level methods directly
......
......@@ -40,6 +40,7 @@ import { getSelectedParams } from './router-reducer/compute-changed-path'
import type { FlightRouterState } from '../../server/app-render/types'
import { useNavFailureHandler } from './nav-failure-handler'
import {
dispatchTraverseAction,
publicAppRouterInstance,
type AppRouterActionQueue,
} from './app-router-instance'
......@@ -418,11 +419,10 @@ function Router({
// TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously
// Without startTransition works if the cache is there for this path
startTransition(() => {
dispatchAppRouterAction({
type: ACTION_RESTORE,
url: new URL(window.location.href),
tree: event.state.__PRIVATE_NEXTJS_INTERNALS_TREE,
})
dispatchTraverseAction(
window.location.href,
event.state.__PRIVATE_NEXTJS_INTERNALS_TREE
)
})
}
......
......@@ -7,7 +7,7 @@
if (process.env.NODE_ENV === 'development') {
const measureName = 'Client Instrumentation Hook'
const startTime = performance.now()
require('private-next-instrumentation-client')
module.exports = require('private-next-instrumentation-client')
const endTime = performance.now()
const duration = endTime - startTime
......@@ -27,5 +27,5 @@ if (process.env.NODE_ENV === 'development') {
)
}
} else {
require('private-next-instrumentation-client')
module.exports = require('private-next-instrumentation-client')
}
......@@ -1092,7 +1092,7 @@ function App<T>({
prerendered: response.S,
})
const actionQueue = createMutableActionQueue(initialState)
const actionQueue = createMutableActionQueue(initialState, null)
const { HeadManagerContext } =
require('../../shared/lib/head-manager-context.shared-runtime') as typeof import('../../shared/lib/head-manager-context.shared-runtime')
......@@ -1159,7 +1159,7 @@ function ErrorApp<T>({
prerendered: response.S,
})
const actionQueue = createMutableActionQueue(initialState)
const actionQueue = createMutableActionQueue(initialState, null)
return (
<ServerInsertedMetadataProvider>
......
import React from 'react'
import Link from 'next/link'
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
<body>
<ul>
<li>
<Link href="/">Home</Link>
</li>
<li>
<Link href="/some-page">Some Page</Link>
</li>
</ul>
{children}
</body>
</html>
)
}
import React from 'react'
export default function Page() {
return <h1>App</h1>
return <h1 id="home">Home</h1>
}
export default function Page() {
return <h1 id="some-page">Some page</h1>
}
......@@ -4,3 +4,8 @@ const start = performance.now()
while (performance.now() - start < 20) {
// Intentionally block for 20ms to test instrumentation timing
}
export function onRouterTransitionStart(href: string, navigateType: string) {
const pathname = new URL(href, window.location.href).pathname
console.log(`[Router Transition Start] [${navigateType}] ${pathname}`)
}
......@@ -49,6 +49,59 @@ describe('Instrumentation Client Hook', () => {
})
})
describe('onRouterTransitionStart', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, 'app-router'),
})
function filterNavigationStartLogs(logs: Array<{ message: string }>) {
const result = []
for (const log of logs) {
if (log.message.startsWith('[Router Transition Start]')) {
result.push(log.message)
}
}
return result
}
it('onRouterTransitionStart fires at the start of a navigation', async () => {
const browser = await next.browser('/')
const linkToSomePage = await browser.elementByCss('a[href="/some-page"]')
await linkToSomePage.click()
await browser.elementById('some-page')
const linkToHome = await browser.elementByCss('a[href="/"]')
await linkToHome.click()
await browser.elementById('home')
expect(filterNavigationStartLogs(await browser.log())).toEqual([
'[Router Transition Start] [push] /some-page',
'[Router Transition Start] [push] /',
])
})
it('onRouterTransitionStart fires at the start of a back/forward navigation', async () => {
const browser = await next.browser('/')
const linkToSomePage = await browser.elementByCss('a[href="/some-page"]')
await linkToSomePage.click()
await browser.elementById('some-page')
await browser.back()
await browser.elementById('home')
await browser.forward()
await browser.elementById('some-page')
expect(filterNavigationStartLogs(await browser.log())).toEqual([
'[Router Transition Start] [push] /some-page',
'[Router Transition Start] [traverse] /',
'[Router Transition Start] [traverse] /some-page',
])
})
})
describe('HMR in development mode', () => {
const { next, isNextDev } = nextTestSetup({
files: path.join(__dirname, 'app-router'),
......
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