Skip to content

fix(instrumentation): read instrumentationClientInject hooks per transition and isolate their errors - #4909

Open
james-elicx wants to merge 6 commits into
mainfrom
fix/instrumentation-client-inject-hooks
Open

james-elicx wants to merge 6 commits into
mainfrom
fix/instrumentation-client-inject-hooks

Conversation

@james-elicx

@james-elicx james-elicx commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Found by the Next.js v16.4.6 deploy suite (run 45649241516): 4 instrumentationClientInject tests in test/e2e/instrumentation-client-hook/instrumentation-client-hook.test.ts failed ("surfaces onRouterTransitionStart from every injected module" and "isolates hook errors between injected modules", once with the default package type and once with type: module).

Root cause

Next.js' next-instrumentation-client-loader emits module.exports = [require(inject0), …, require(user)]. At each transition, callHooks (client/components/router-transition.ts) calls hooks.onRouterTransitionStart?.(url, type, event) on every module in its own try/catch, which logs An instrumentation-client router transition hook failed:

  • require() of a CommonJS module returns its live module.exports. That lets the fixture's inject-late-hook.cjs install onRouterTransitionStart after load.
  • One throwing hook doesn't stop the other modules' hooks or the navigation.
  • Without experimental.instrumentationClientRouterTransitionEvents, the third argument is null.

vinext's generated module did import * as ns for every inject and tested typeof ns.onRouterTransitionStart. A CommonJS module's namespace only copies the keys present at load, so the late hook never ran. Nothing caught a throwing hook either, so it aborted the navigation (waitForSelector('#some-page') timed out).

Fix

  • The generated private-next-instrumentation-client module namespace-imports every inject, as before. It now reads each module's hook when a transition starts and catches and logs each hook's error with Next's message.
  • When an inject's namespace has no onRouterTransitionStart, the hook is read from the namespace's default. For CommonJS, that default is the live module.exports under Rolldown's interop in builds and Vite's optimized-dep interop in dev ({...module.exports, default: module.exports}). So a hook installed after load is found in both, the same way Next's require() finds it. There is no build-time CommonJS detection, so no inject can be misclassified.
    • One known difference: an ESM inject with no named onRouterTransitionStart but a default export object that has one gets that hook called, where Next.js ignores it. A named export always wins.
  • Each module's hook is selected and read inside that module's try, so an inject whose CommonJS namespace has a throwing live getter (Rolldown's interop) is logged and skipped like a throwing hook.
  • Bare-specifier injects are added to the client optimizer's startup includes. Only the generated module imports them, and the dependency scan never crawls it, so dev would otherwise discover them on the first request, then re-optimize and reload.
  • notifyAppRouterTransitionStart passes null as the third argument and catches a throwing user hook too, as callHooks does when no injects are configured.

Regression test

  • tests/fixtures/app-basic now configures three injects, ported from Next's inject fixture:
    • a local CommonJS file that installs its hook after load;
    • the same late hook from a bare CommonJS package (__test_packages__/fake-instrumentation-inject), which dev serves through the deps optimizer;
    • an ESM module whose hook throws once a spec opts in.
  • New tests/e2e/app-router/instrumentation-client-inject.spec.ts runs in the app-router (dev) and app-router-isr-prod (prod build) projects. It installs both late hooks, makes the ESM hook throw, navigates, and checks three things: every hook ran in order, the late hook received null, and exactly one An instrumentation-client router transition hook failed error was logged.
    • With the pre-fix source (git restore --source=origin/main on the implementation files, then rebuild), the spec fails: the throwing hook aborts the navigation and #instrumentation-client-some-page never shows. With the first commit's build-time classification (e8ae234), it fails in dev because the package's late hook is missing. With the fix it passes in dev and prod. The existing instrumentation-client.spec.ts (including dev HMR) still passes.
  • tests/instrumentation.test.ts adds generator and hook-state unit tests:
    • a late hook on the live default, with a named export taking precedence;
    • a comment-only module.exports inject;
    • a null third argument and a logged hook error;
    • a throwing live getter on an inject's hook export.
  • tests/build-optimization.test.ts checks that app-basic's bare inject is pre-bundled for the client at startup, and that relative injects are not.
  • tests/after-response-close-worker.test.ts builds app-basic with cf-app-basic's node_modules, so it drops the local inject package from its copied next.config.ts, as it already drops the routes that use local packages.
  • vp check is clean.

Deploy suite (local, ds-run.sh)

  • v16.4.6 instrumentation-client-hook.test.ts: 8/17 on main → 12/17. The 4 inject tests flip fail→pass, with no pass→fail.
  • The 5 tests still failing are the router transition start context group, which needs experimental.instrumentationClientRouterTransitionEvents. That's separate work.
  • v16.2.6 instrumentation-client-hook.test.ts: 6/6 pass on this branch, with no pass→fail.

Performance

No change to the per-module transform path or to build-time work. The virtual module's runtime adds one property check per inject per navigation. CI's paired perf comparison covers build time and dev cold start.

…sition and isolate their errors

Next.js require()s each injected module and calls its onRouterTransitionStart when a transition starts, inside its own try/catch. vinext imported CommonJS injects as snapshotted namespaces, so hooks installed after load never ran, and a throwing hook broke the navigation. Import CommonJS injects' live module.exports, read each hook per transition, log hook failures like Next, and pass the null third argument Next passes without the transition-events flag.
@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@vinext/cloudflare

npm i https://pkg.pr.new/@vinext/cloudflare@4909

create-vinext-app

npm i https://pkg.pr.new/create-vinext-app@4909

@vinext/types

npm i https://pkg.pr.new/@vinext/types@4909

vinext

npm i https://pkg.pr.new/vinext@4909

@cloudflare/workers-response-store

npm i https://pkg.pr.new/@cloudflare/workers-response-store@4909

commit: 56f6494

@github-actions

Copy link
Copy Markdown
Contributor
Example Preview Production Original
app-router-cloudflare preview production
pages-router-cloudflare preview production
app-router-playground preview production original
realworld-api-rest preview production
nextra-docs-template preview production
benchmarks preview production
hackernews preview production original
response-store-demo preview production
workers-cache preview production
kv preview production
static-assets-cache preview production
static-assets-pages preview production
static-assets-pages-i18n preview production
static-export preview production
web preview production

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Performance benchmarks

Compared 56f6494 against base 219c880 using alternating same-runner rounds. Next.js was unchanged and skipped.

3 improved · 0 regressed · 4 within ±1.5%

Scenario Framework Baseline Current Change
Client bundle size (gzip) vinext 157.3 KB 157.3 KB ⚫ +0.0%
Client entry size (gzip) vinext 145.5 KB 145.5 KB ⚫ +0.0%
Dev server cold start vinext 2.02 s 1.94 s 🟢 -3.6%
Dev server cold start (large Pages Router app) vinext 14.38 s 13.57 s 🟢 -5.7%
Production build time vinext 2.28 s 2.24 s 🟢 -1.7%
RSC entry closure size (gzip) vinext 150.6 KB 150.6 KB ⚫ +0.0%
Server bundle size (gzip) vinext 262.8 KB 262.9 KB ⚫ +0.0%

View detailed results and traces

🟢 improvement · 🔴 regression · ⚫ change below 1.5% · paired base/head

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head e8ae23488b4bfb8ba05b2aa3bfa4abf4d3b7cb33 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

* plain script, which the namespace import also covers.
*/
export function isCommonJsInstrumentationClientInject(code: string, id: string): boolean {
if (!mayAssignCommonJsExports(code)) return false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mayAssignCommonJsExports() deliberately has textual false positives, but here a match changes the generated import from a namespace import to a required default import. A valid side-effect-only inject containing // module.exports = {} (or that text in a string/regex) has no ESM syntax, so this returns true; the generated build then fails with MISSING_EXPORT: default is not exported. Next.js accepts the same module through require(). Please detect an actual CommonJS export assignment from the parsed AST (and cover comment/string matches) before selecting a default import.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8bb6538 by dropping the build-time CommonJS classification entirely. isCommonJsInstrumentationClientInject and mayAssignCommonJsExports are gone, so no default import is ever generated and a side-effect-only inject with module.exports in a comment or string can't hit MISSING_EXPORT. Every inject is namespace-imported. At each transition the generated module reads the hook from the namespace, or from its default when the namespace lacks it. default is the live module.exports under both Rolldown's and Vite dev's CommonJS interop. tests/instrumentation.test.ts covers this with a comment-only // module.exports = {} inject.

Comment thread packages/vinext/src/index.ts Outdated
const importer = path.join(root, "package.json");
const injects = await Promise.all(
clientInjectSpecifiers.map(async (specifier) => {
const resolved = await this.resolve(specifier, importer);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In client dev, resolving a bare CommonJS package here returns its optimized .vite/deps/<pkg>.js?v=... module rather than the package's original .cjs source. That optimized file has ESM syntax, so commonjs becomes false and the generated module namespace only exposes the live CommonJS export object under default; a late-added onRouterTransitionStart is therefore never found. Production resolves the original file and works, leaving dev/prod behavior inconsistent for package injects. Please classify the original package source (or otherwise select the optimized module's default export), with a bare-package dev regression test.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8bb6538. The generated module no longer classifies the resolved file. It namespace-imports each inject and, when the namespace has no onRouterTransitionStart, reads it from default. For an optimized CommonJS dep, Vite's dev interop gives {...module.exports, default: module.exports}, so a hook added after load is found on default, as it is in production. Regression test: app-basic now also injects fake-instrumentation-inject, a bare CommonJS package (__test_packages__) whose hook is installed after load, and tests/e2e/app-router/instrumentation-client-inject.spec.ts expects its log. On e8ae234 that spec fails in dev, because the package hook is missing. It passes on this head in dev (app-router) and prod (app-router-isr-prod).

One known difference from webpack's require(): an ESM inject that exports no named onRouterTransitionStart but has a default export object with one would have that hook called. Next.js would ignore it. A named export always wins, which the unit test also covers.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Review: 2 findings.

Posted 2 actionable inline comments.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head 8bb6538e4917a2a9e18e523996b4d84dac015696 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

"",
"export function onRouterTransitionStart(url, type, event) {",
" const modules = [",
" ...__vinext_inject_modules.map(__vinext_inject_hooks),",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The module selection happens before the per-module try. In a production build Rolldown wraps CommonJS namespaces with live getters; an enumerable onRouterTransitionStart getter on module.exports is therefore invoked by namespace.onRouterTransitionStart here and can throw before the loop starts. The outer notifyAppRouterTransitionStart catch keeps navigation alive, but every later inject and the user hook are skipped, whereas Next.js performs the property read inside callHooks’ per-module try. Move this selection/property access into the per-module guarded block and cover a throwing getter.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b4bc242: hook selection (__vinext_inject_hooks(namespace), which reads namespace.onRouterTransitionStart) now runs inside each module's try, along with the call, as in Next.js's callHooks. A throwing live getter is logged with An instrumentation-client router transition hook failed, and the later injects and the user hook still run. New test: "isolates a CommonJS inject whose hook export is a throwing getter". It replaces the generated namespace import with a Rolldown-style object that has a throwing getter, and fails on the previous generator.

"./instrumentation-client-inject-late-hook.cjs",
// The same late hook from a CommonJS package, which dev serves through
// the deps optimizer.
"fake-instrumentation-inject",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This bare dependency is only imported by the generated private-next-instrumentation-client virtual module, while that module is excluded from optimization and the client scanner only crawls the app/instrumentation source entries. Vite therefore cannot discover this CommonJS package at startup; the first browser request discovers it late, re-bundles dependencies, and may reload every page sharing the dev server, making the parallel app-router project flaky. Seed configured bare injects in the client optimizer (or at minimum add this fixture package to optimizeDeps.include) so this test exercises optimized interop without a first-request reload.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b4bc242, in the product rather than only the fixture: configResolved adds every bare-specifier instrumentationClientInject entry to each discovering client optimizer's startup includes, next to vinext's other optional client includes. Relative and absolute paths are skipped, as are shim specifiers and noDiscovery optimizers. Pages-only clients are covered as well, since the generated module is uncrawled there too. Running the inject spec locally, fake-instrumentation-inject now shows up under optimized in app-basic's dep metadata, not discovered. New test in tests/build-optimization.test.ts against the checked-in app-basic config, which fails on the previous source.

Also in this push: CI's Vitest (unit 2/3) failure. after-response-close-worker.test.ts builds a copy of app-basic with cf-app-basic's node_modules, which lacks app-basic's local file: packages. It already drops the routes that use them, so it now also drops the bare inject from the copied next.config.ts.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Review: 2 findings.

Posted 2 actionable inline comments. tests/instrumentation.test.ts passes all 48 tests.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head b4bc2424506abdc2ff6489b62782048699c6522f without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Since last review: 2 resolved, 0 still open, 0 new.
LGTM!

github run

@james-elicx
james-elicx marked this pull request as ready for review November 26, 2026 07:08

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of f13d0aaa.

This review, of b4bc2424

💬 Approved with comments — The fix is correct and well tested in dev and prod. The only note is an INFO: alias-style inject specifiers get added to the optimizer's startup includes.

Findings: 1 info (1 is an inline comment on the diff)

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


📋 Code Quality: 💬 1 info

The fix is sound and well tested. One low-impact edge case in the bare-inject filter for optimizer includes.

Recommendation: 💬 Optional Nits

  • [INFO] Bare-inject filter for optimizer includes also matches alias and subpath-import specifiers (packages/vinext/src/index.ts:5042)
View full review

The generator, the per-module try/catch and the null third argument match Next's callHooks. The default fallback guards against null and non-object values. The new tests cover late CommonJS hooks, a named export taking precedence, throwing getters, error logging and startup includes.

  • packages/vinext/src/index.ts:5041-5043: bareInstrumentationClientInjects treats any specifier that doesn't start with . and isn't absolute as an npm package. That also matches alias and subpath-import specifiers such as @/inject or #inject, so they end up in the client optimizeDeps.include.

✅ All other checks passed

🔒 Security: ✅ LGTM

No security concerns in this change.


📖 AGENTS.md: ✅ LGTM

This pull request does not touch the agent guidelines, and the change follows them.


⚡ Performance: ✅ LGTM

Each navigation adds one property lookup and one try/catch per inject. The build-time and startup changes are small.


📝 Documentation: ✅ LGTM

No documentation issues.


Reviewed commit: b4bc2424

Comment thread packages/vinext/src/index.ts Outdated
// the optimizer never crawls, imports a bare inject, so the first
// request would discover it late, re-optimize and reload.
const bareInstrumentationClientInjects = nextConfig.instrumentationClientInject.filter(
(spec) => !spec.startsWith(".") && !path.isAbsolute(spec) && !isExcludedShim(spec),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ INFO · Code Quality

Bare-inject filter for optimizer includes also matches alias and subpath-import specifiers

This filter treats any specifier that doesn't start with . and isn't absolute as a package, so alias specifiers (@/inject, ~/inject) and subpath imports (#inject) are added to the client optimizeDeps.include too. Vite may then log "Failed to resolve dependency" at startup or pre-bundle a source file. The generated module still imports the specifier normally, so this doesn't break anything. If it matters, consider only including specifiers that resolve into node_modules.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f13d0aa: only specifiers shaped like npm package names (optionally scoped, with an optional subpath) are added to the optimizer's startup includes. The new isPackageInjectSpecifier in client/instrumentation-client-inject.ts skips path aliases (@/x, ~/x), subpath imports (#x), and relative and absolute paths, so none of them reaches the optimizer. The unit test "treats only package names as pre-bundlable injects" covers both sides.

@james-elicx

Copy link
Copy Markdown
Member Author

clanky review

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head f13d0aaa1e697e740e1ae70e8c231ef3b330803d without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of eb0e832a.

This review, of f13d0aaa

✅ Approved — The earlier INFO is fixed by isPackageInjectSpecifier, and the code at this commit has no new issues.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No security concerns in this change.


📖 AGENTS.md: ✅ LGTM

The change follows the repository guidelines: the inject fixtures are ported from Next.js, and the new behaviour is tested in both dev and prod.


📋 Code Quality: ✅ LGTM

isPackageInjectSpecifier (packages/vinext/src/client/instrumentation-client-inject.ts) accepts only npm-package-shaped specifiers (optionally scoped, with an optional subpath). packages/vinext/src/index.ts applies it, together with the shim exclusion, before adding injects to the client optimizer's includes. Path aliases, subpath imports and relative or absolute paths are skipped, and the new unit test covers both sides. The generated module still reads and calls each hook inside its own try, and the default fallback guards against null and non-object values.


⚡ Performance: ✅ LGTM

Each navigation adds one property lookup and one try/catch per inject. The optimizer-include filter runs once at config time, over the configured inject list.


📝 Documentation: ✅ LGTM

No documentation issues.


Reviewed commit: f13d0aaa

`const __vinext_inject_modules = [${modules.join(", ")}];`,
"",
"function __vinext_inject_hooks(namespace) {",
" if (namespace.onRouterTransitionStart !== undefined) return namespace;",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

__vinext_inject_hooks reads namespace.onRouterTransitionStart here to select the container, then line 106 reads it again to call it. For CommonJS interop this can be a live getter (the code explicitly supports that case), whereas Next.js's optional call reads the property once. A stateful getter can return a hook on the first read and throw or return a different hook on the second, changing behavior. Read the property once inside the existing per-module try and invoke the cached value; retain the default fallback when the first value is undefined.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in eb0e832: the generated fan-out reads onRouterTransitionStart once per module per transition, inside the per-module try, and calls the cached value with the right receiver (hook?.call(hooks, ...)). The default fallback applies only when that first read is undefined. The user's own module is read directly, without the fallback. New test: "reads a CommonJS inject's hook once per transition". A stateful getter returns the hook on the first read and throws on the second; the hook runs once and nothing is logged. The test fails on the previous generator.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Review: 1 findings.

Posted 1 actionable inline comment. tests/instrumentation.test.ts passes all 50 tests.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head eb0e832a7891a77f28e92a094b8dde74372ea091 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by the review of 56f64947.

This review, of eb0e832a

✅ Approved — Since the previous review, the generated fan-out reads each inject's hook once per transition, inside that module's try, and calls it with the right receiver. That fixes the last open point, and the change has no new issues.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

The inject specifiers come from the project's own next.config and are written into the generated module with JSON.stringify. The package-name filter only affects which dependencies are pre-bundled. The fixtures and the lockfile entry are used only by tests.


📖 AGENTS.md: ✅ LGTM

The change follows the repository guidelines. The inject fixtures are ported from Next.js, and the behaviour is tested in both dev and prod.


📋 Code Quality: ✅ LGTM

__vinext_inject_hook (packages/vinext/src/client/instrumentation-client-inject.ts) now reads namespace.onRouterTransitionStart once per transition. It falls back to namespace.default only when that read is undefined, and only when default is a non-null object or function. The read and the call (hook?.call(hooks, url, type, event)) both run inside the per-module try, so a throwing live getter or a throwing hook is logged with Next's message and the later modules still run. The user's own module is read directly, without the fallback.

The new unit test uses a stateful getter that throws on a second read, so it would fail if the generated code read the hook twice. The other tests cover a late hook on default, a named export taking precedence, a comment-only inject, and a throwing getter.


⚡ Performance: ✅ LGTM

Each navigation adds one property read and one try/catch per inject. The optimizer-include filter runs once, when the config is resolved.


📝 Documentation: ✅ LGTM

No documentation issues.


Reviewed commit: eb0e832a

"// namespace's export can be a live getter.",
"function __vinext_inject_hook(namespace) {",
" const hook = namespace.onRouterTransitionStart;",
" if (hook !== undefined) return { hooks: namespace, hook };",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fallback still reads a live CommonJS getter twice when the first read returns undefined: line 92 reads the namespace getter, then line 96 reads the same module.exports property through default. Next.js’s hooks.onRouterTransitionStart?.(...) reads it once. I reproduced a stateful getter returning undefined then a function as 2 reads/1 call here versus 1 read/0 calls in Next’s expression. Select the fallback based on whether the namespace has the export key, rather than the first value, so a present-but-undefined getter is not retried.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 56f6494. The fallback now depends on whether the namespace has the onRouterTransitionStart key (in), not on the first value. A present export is read once, even when it returns undefined, and default is read only when the key is missing. New test: "doesn't read a present CommonJS hook export again through default". A shared getter returns undefined and then a hook; it is read once and the hook is not called. The test fails on the previous generator.

" index < __vinext_inject_modules.length",
" ? __vinext_inject_hook(__vinext_inject_modules[index])",
` : { hooks: __vinj_${userSlot}, hook: __vinj_${userSlot}.onRouterTransitionStart };`,
" hook?.call(hooks, url, type, event);",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hook?.call(...) is not equivalent to Next.js’s direct optional method call because a function can override its own call property (or be a proxy that traps that lookup). In that case this invokes the replacement instead of the hook; I verified this with hook.call = otherFunction. Use Reflect.apply(hook, hooks, [url, type, event]) (inside the existing try) to preserve the receiver while invoking the cached function’s [[Call]] directly.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 56f6494. The fan-out now calls Reflect.apply(hook, hooks, [url, type, event]) when the hook is not nullish, inside the same per-module try. A non-callable value still throws a TypeError there and is logged. New test: "calls a hook that overrides its own call property". It fails on the previous generator.

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Review: 2 findings.

Posted 2 actionable inline comments. tests/instrumentation.test.ts passes all 51 tests.

github run

@james-elicx

Copy link
Copy Markdown
Member Author

/bigbonk review for issues
Please review exact head 56f64947c1d6348839d898a6ff33946a3489d032 without modifying or pushing the branch. Report all actionable findings within your 8-minute time limit.

@clanky-the-clanker clanky-the-clanker Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Approved — Since the last review, the fallback to default uses an in check, so a present export is read only once, and the hook is called through Reflect.apply. Both changes match Next.js's single optional call, and the new tests cover them. No issues found.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

The inject specifiers come from the project's own next.config and are written into the generated module with JSON.stringify. Nothing in this change affects a security boundary.


📖 AGENTS.md: ✅ LGTM

The change follows the repository guidelines. The fixtures are ported from Next.js's inject fixture, and the behaviour is covered in both dev and prod.


📋 Code Quality: ✅ LGTM

Changes since the last review:

  • "onRouterTransitionStart" in namespace does not invoke a live getter, so a present export is read once, even when its value is undefined. default is read only when the key is missing.
  • Reflect.apply(hook, hooks, [url, type, event]) calls the hook itself, even when the hook overrides its own call. A non-callable value throws a TypeError inside the per-module try, so it is logged and the later modules still run.
  • The user's module is read directly, without the fallback, which matches Next.js's hooks.onRouterTransitionStart?.().

The new tests ("doesn't read a present CommonJS hook export again through default" and "calls a hook that overrides its own call property") exercise exactly these two behaviours.


⚡ Performance: ✅ LGTM

Each navigation adds one in check, one property read and one try/catch per inject, which is negligible. The optimizer-include filter runs once, when the config is resolved.


📝 Documentation: ✅ LGTM

No documentation issues.


Reviewed commit: 56f64947

@ask-bonk

ask-bonk Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

LGTM!

github run

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant