Repository navigation
fix(instrumentation): read instrumentationClientInject hooks per transition and isolate their errors - #4909
fix(instrumentation): read instrumentationClientInject hooks per transition and isolate their errors#4909james-elicx wants to merge 6 commits into
Conversation
…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.
@vinext/cloudflare
create-vinext-app
@vinext/types
vinext
@cloudflare/workers-response-store
commit: |
|
Performance benchmarksCompared 3 improved · 0 regressed · 4 within ±1.5%
View detailed results and traces 🟢 improvement · 🔴 regression · ⚫ change below 1.5% · paired base/head |
|
/bigbonk review for issues |
| * plain script, which the namespace import also covers. | ||
| */ | ||
| export function isCommonJsInstrumentationClientInject(code: string, id: string): boolean { | ||
| if (!mayAssignCommonJsExports(code)) return false; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| const importer = path.join(root, "package.json"); | ||
| const injects = await Promise.all( | ||
| clientInjectSpecifiers.map(async (specifier) => { | ||
| const resolved = await this.resolve(specifier, importer); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Review: 2 findings. Posted 2 actionable inline comments. |
…e exports in dev and prod
|
/bigbonk review for issues |
| "", | ||
| "export function onRouterTransitionStart(url, type, event) {", | ||
| " const modules = [", | ||
| " ...__vinext_inject_modules.map(__vinext_inject_hooks),", |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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", |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Review: 2 findings. Posted 2 actionable inline comments. |
…bundle bare injects
|
/bigbonk review for issues |
|
Since last review: 2 resolved, 0 still open, 0 new. |
There was a problem hiding this comment.
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:bareInstrumentationClientInjectstreats 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@/injector#inject, so they end up in the clientoptimizeDeps.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
| // 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), |
There was a problem hiding this comment.
ℹ️ 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.
There was a problem hiding this comment.
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.
|
clanky review |
|
/bigbonk review for issues |
There was a problem hiding this comment.
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;", |
There was a problem hiding this comment.
__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.
There was a problem hiding this comment.
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.
|
Review: 1 findings. Posted 1 actionable inline comment. |
|
/bigbonk review for issues |
There was a problem hiding this comment.
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 };", |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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);", |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Review: 2 findings. Posted 2 actionable inline comments. |
|
/bigbonk review for issues |
There was a problem hiding this comment.
✅ 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 namespacedoes not invoke a live getter, so a present export is read once, even when its value isundefined.defaultis read only when the key is missing.Reflect.apply(hook, hooks, [url, type, event])calls the hook itself, even when the hook overrides its owncall. A non-callable value throws aTypeErrorinside the per-moduletry, 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
|
LGTM! |
Found by the Next.js v16.4.6 deploy suite (run 45649241516): 4
instrumentationClientInjecttests intest/e2e/instrumentation-client-hook/instrumentation-client-hook.test.tsfailed ("surfaces onRouterTransitionStart from every injected module" and "isolates hook errors between injected modules", once with the default package type and once withtype: module).Root cause
Next.js'
next-instrumentation-client-loaderemitsmodule.exports = [require(inject0), …, require(user)]. At each transition,callHooks(client/components/router-transition.ts) callshooks.onRouterTransitionStart?.(url, type, event)on every module in its owntry/catch, which logsAn instrumentation-client router transition hook failed:require()of a CommonJS module returns its livemodule.exports. That lets the fixture'sinject-late-hook.cjsinstallonRouterTransitionStartafter load.experimental.instrumentationClientRouterTransitionEvents, the third argument isnull.vinext's generated module did
import * as nsfor every inject and testedtypeof 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
private-next-instrumentation-clientmodule 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.onRouterTransitionStart, the hook is read from the namespace'sdefault. For CommonJS, thatdefaultis the livemodule.exportsunder 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'srequire()finds it. There is no build-time CommonJS detection, so no inject can be misclassified.onRouterTransitionStartbut adefaultexport object that has one gets that hook called, where Next.js ignores it. A named export always wins.try, so an inject whose CommonJS namespace has a throwing live getter (Rolldown's interop) is logged and skipped like a throwing hook.notifyAppRouterTransitionStartpassesnullas the third argument and catches a throwing user hook too, ascallHooksdoes when no injects are configured.Regression test
tests/fixtures/app-basicnow configures three injects, ported from Next'sinjectfixture:__test_packages__/fake-instrumentation-inject), which dev serves through the deps optimizer;tests/e2e/app-router/instrumentation-client-inject.spec.tsruns in theapp-router(dev) andapp-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 receivednull, and exactly oneAn instrumentation-client router transition hook failederror was logged.git restore --source=origin/mainon the implementation files, then rebuild), the spec fails: the throwing hook aborts the navigation and#instrumentation-client-some-pagenever 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 existinginstrumentation-client.spec.ts(including dev HMR) still passes.tests/instrumentation.test.tsadds generator and hook-state unit tests:default, with a named export taking precedence;module.exportsinject;nullthird argument and a logged hook error;tests/build-optimization.test.tschecks 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.tsbuilds app-basic with cf-app-basic'snode_modules, so it drops the local inject package from its copiednext.config.ts, as it already drops the routes that use local packages.vp checkis clean.Deploy suite (local,
ds-run.sh)instrumentation-client-hook.test.ts: 8/17 on main → 12/17. The 4 inject tests flip fail→pass, with no pass→fail.router transition start contextgroup, which needsexperimental.instrumentationClientRouterTransitionEvents. That's separate work.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.