Repository navigation
Description
Is there an existing issue for this?
- I searched the existing issues and PRs, including
Sentry.captureException/captureMessagebreak Next.js prerendering with Cache Components enabled #21333, fix(core): UsesafeDateNowcalls fornew Date()reads #21351, captureException duringnext buildprerender fails cacheComponents routes (safe-random runner never registered in build workers) #21510 and fix(next): Wrap all Random APIs with a safe runner #18700. - I reviewed the documentation and contribution guidelines.
- I reproduced this with the latest published SDK, 11.13.0.
How do you use Sentry?
Sentry SaaS (sentry.io).
Which SDK are you using?
@sentry/nextjs with @sentry/profiling-node (package: profiling-node).
SDK Version
Originally observed with 11.11.0; the deterministic reproduction below also fails with 11.13.0, in both CommonJS and ESM.
Framework Version
Next.js 16.4.5, cacheComponents: true; Node.js 26.13.0, macOS arm64.
Problem
Closing the last sampled span during an on-demand prerender can synchronously flush a CPU profile. The profiler's separate createEventEnvelopeHeaders() still builds sent_at with a zero-argument new Date(), which reads the render clock and violates Next.js Cache Components' prerender restrictions. We observed the production error on course and blog-tag pages; the server bundle pointed to the span-end callback that flushes the profile.
The current profiling-node helper remains separate from core's event envelope helper. Its profile envelope is constructed before client.sendEnvelope(), so changing a transport or beforeEnvelope hook would be too late.
Steps to reproduce
The self-contained example below uses the real native CPU profiler and the actual Next.js SDK safe-context setup. It supplies an isolated client that only collects envelopes, a simulated Next.js work-unit store, and a guarded clock to make the restriction deterministic. It does not start a Next.js server or send telemetry.
- In an empty directory, install
@sentry/nextjs@11.13.0,@sentry/profiling-node@11.13.0,next@16.4.5,react@19.3.1andreact-dom@19.3.1with pnpm. Allow the official@sentry/node-cpu-profilerinstall script if pnpm asks. - Save the following file as
repro.mjs. - Run
node repro.mjs commonjsandnode repro.mjs module.
Deterministic native-profiler reproduction
import assert from "node:assert/strict";
import { AsyncLocalStorage } from "node:async_hooks";
import { createRequire } from "node:module";
import { performance } from "node:perf_hooks";
const require = createRequire(import.meta.url);
const workUnitStorage = new AsyncLocalStorage();
globalThis[Symbol.for("@next/work-unit-async-storage@profiling-test")] = workUnitStorage;
require("@sentry/nextjs");
const { nodeProfilingIntegration } =
process.argv[2] === "commonjs" ? require("@sentry/profiling-node") : await import("@sentry/profiling-node");
const hooks = new Map();
const envelopes = [];
const integration = nodeProfilingIntegration();
integration.setup({
getOptions: () => ({ profileSessionSampleRate: 1, profileLifecycle: "trace" }),
on(name, callback) {
hooks.set(name, callback);
return () => hooks.delete(name);
},
getDsn: () => undefined,
getSdkMetadata: () => undefined,
sendEnvelope(envelope) {
envelopes.push(envelope);
return Promise.resolve({ statusCode: 200 });
},
});
const span = {
spanContext: () => ({ traceId: "1".repeat(32), spanId: "2".repeat(16), traceFlags: 1 }),
};
const OriginalDate = Date;
const startedAt = OriginalDate.now();
globalThis.Date = new Proxy(OriginalDate, {
construct(target, args, newTarget) {
if (args.length === 0) {
assert.equal(workUnitStorage.getStore(), undefined, "Profiling must not read new Date() during prerender");
}
return Reflect.construct(target, args, newTarget);
},
get(target, property, receiver) {
if (property === "now") {
return () => {
assert.equal(workUnitStorage.getStore(), undefined, "Profiling must not read Date.now() during prerender");
return OriginalDate.now();
};
}
return Reflect.get(target, property, receiver);
},
});
try {
workUnitStorage.run("prerender", () => {
hooks.get("spanStart")(span);
const start = performance.now();
let work = 0;
while (performance.now() - start < 40) {
work += Math.sin(work + 0.1);
}
hooks.get("spanEnd")(span);
});
} finally {
globalThis.Date = OriginalDate;
}
assert.equal(envelopes.length, 1);
const sentAt = envelopes[0][0].sent_at;
assert.ok(Date.parse(sentAt) >= startedAt && Date.parse(sentAt) <= Date.now());
process.stdout.write(JSON.stringify({ type: envelopes[0][1][0][0].type, sentAt }));Expected result
The profile can be flushed without reading the ambient prerender clock directly. A valid profile_chunk envelope is collected with an ISO sent_at timestamp. Profiling and the page's rendering strategy stay unchanged.
Actual result
Both module formats fail with:
AssertionError [ERR_ASSERTION]: Profiling must not read new Date() during prerender
at createEventEnvelopeHeaders
at makeProfileChunkEnvelope
at ContinuousProfiler._flush
at ContinuousProfiler._stopChunkProfiling
Related fixes and why this case is still uncovered
Sentry.captureException/captureMessagebreak Next.js prerendering with Cache Components enabled #21333 was fixed by fix(core): UsesafeDateNowcalls fornew Date()reads #21351 in 10.57.0. That fix changed clock reads in core and added guarded-clock coverage there. It did not change profiling-node's separate helper forprofile_chunkenvelopes, so upgrading past that release does not cover this path.- captureException during
next buildprerender fails cacheComponents routes (safe-random runner never registered in build workers) #21510, fixed by fix(nextjs): Register safe random ID context at module load #21573 in 10.59.0, concerns safe random-ID setup in build prerender workers. Here the Next.js safe runner is registered and active; the remaining read is a barenew Date()in profiling-node. - fix(nextjs): Don't abort Cache Components renders on Cloudflare Workers when requests overlap #25315 improves how the Next.js SDK exits its render store on Next.js 16.4+ and handles Cloudflare request lifetimes. The reproduction uses the current Next.js runner; profiling-node bypasses it for this timestamp.
Proposed approach and request for a maintainer's go-ahead
I would like to contribute a small draft PR replacing this timestamp read with new Date(safeDateNow()).toISOString(), importing the existing core helper through its internal export, plus regression coverage for the profiling envelope under a guarded clock.
This follows the responsibility split described in #18700: the Next.js SDK installs the safe runner, and shared SDK code uses the clock/random helpers without importing Next.js. The discussion with gnoff also cautions against broad context escapes that can hide non-determinism affecting rendered or cached values. Here the proposed escape is limited to the telemetry envelope timestamp. I am treating that discussion as design precedent, not as prior approval for this change.
Per External contributors, I have not written the SDK patch or opened a PR. Would a maintainer be happy for me to prepare this focused fix against develop?
Metadata
Metadata
Assignees
Projects
- StatusShow more project fieldsWaiting for: Product Owner
Activity
linear-code commentedon Nov 16, 2026
JS-4107