mirror of
https://github.com/hanzoai/next.js.git
synced 2026-10-30 14:46:38 +00:00
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 #
-->
159 lines
4.8 KiB
TypeScript
159 lines
4.8 KiB
TypeScript
import { nextTestSetup } from 'e2e-utils'
|
|
import { retry } from 'next-test-utils'
|
|
import path from 'path'
|
|
|
|
describe('Instrumentation Client Hook', () => {
|
|
const testCases = [
|
|
{
|
|
name: 'With src folder',
|
|
appDir: 'app-with-src',
|
|
shouldLog: false,
|
|
},
|
|
{
|
|
name: 'App Router',
|
|
appDir: 'app-router',
|
|
shouldLog: true,
|
|
},
|
|
{
|
|
name: 'Pages Router',
|
|
appDir: 'pages-router',
|
|
shouldLog: false,
|
|
},
|
|
]
|
|
|
|
testCases.forEach(({ name, appDir, shouldLog }) => {
|
|
describe(name, () => {
|
|
const { next, isNextDev } = nextTestSetup({
|
|
files: path.join(__dirname, appDir),
|
|
})
|
|
|
|
it(`should execute instrumentation-client from ${name.toLowerCase()} before hydration`, async () => {
|
|
const browser = await next.browser('/')
|
|
|
|
const instrumentationTime = await browser.eval(
|
|
`window.__INSTRUMENTATION_CLIENT_EXECUTED_AT`
|
|
)
|
|
const hydrationTime = await browser.eval(`window.__NEXT_HYDRATED_AT`)
|
|
|
|
expect(instrumentationTime).toBeDefined()
|
|
expect(hydrationTime).toBeDefined()
|
|
expect(instrumentationTime).toBeLessThan(hydrationTime)
|
|
expect(
|
|
(await browser.log()).some((log) =>
|
|
log.message.startsWith(
|
|
'[Client Instrumentation Hook] Slow execution detected'
|
|
)
|
|
)
|
|
).toBe(isNextDev && shouldLog)
|
|
})
|
|
})
|
|
})
|
|
|
|
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'),
|
|
})
|
|
|
|
if (isNextDev) {
|
|
it('should reload instrumentation-client when modified', async () => {
|
|
const browser = await next.browser('/')
|
|
const initialTime = await browser.eval(
|
|
`window.__INSTRUMENTATION_CLIENT_EXECUTED_AT`
|
|
)
|
|
expect(initialTime).toBeDefined()
|
|
|
|
// Modify the instrumentation-client.ts file
|
|
const instrumentationPath = 'instrumentation-client.ts'
|
|
|
|
const originalContent = await next.readFile(instrumentationPath)
|
|
|
|
await next.patchFile(
|
|
instrumentationPath,
|
|
`
|
|
window.__INSTRUMENTATION_CLIENT_EXECUTED_AT = Date.now();
|
|
window.__INSTRUMENTATION_CLIENT_UPDATED = true;
|
|
`
|
|
)
|
|
|
|
await retry(async () => {
|
|
// Check if the updated instrumentation client was executed
|
|
const updatedFlag = await browser.eval(
|
|
`window.__INSTRUMENTATION_CLIENT_UPDATED`
|
|
)
|
|
expect(updatedFlag).toBe(true)
|
|
|
|
// Verify new execution time
|
|
const newTime = await browser.eval(
|
|
`window.__INSTRUMENTATION_CLIENT_EXECUTED_AT`
|
|
)
|
|
expect(newTime).toBeDefined()
|
|
expect(newTime).toBeGreaterThan(initialTime)
|
|
})
|
|
|
|
// Restore the original file
|
|
await next.patchFile(instrumentationPath, originalContent)
|
|
})
|
|
} else {
|
|
// Add a dummy test when not in dev mode
|
|
it('skips tests in non-dev mode', () => {
|
|
console.log(
|
|
'Skipping instrumentation-client-hook tests in non-dev mode'
|
|
)
|
|
})
|
|
}
|
|
})
|
|
})
|