Repository navigation
fix(env): clientEnv is empty in the browser, so client Sentry never initializes - #771
Conversation
`clientEnv` was `ClientEnvSchema.parse(process.env)`. Next substitutes literal `process.env.<KEY>` member expressions and nothing else, so a bare `process.env` in a browser bundle is the empty stub from `next/dist/compiled/process`. Every `NEXT_PUBLIC_*` value read through it was `undefined` there, while reading as configuration that works. Enumerating the keys into a literal object would have fixed the parse and re-armed the trap: that enumeration can drift from the schema silently, and the drift looks the same as the bug. Nothing is lost by removing the value. `ServerEnvSchema` extends `ClientEnvSchema`, so the server already validates these four variables and reads them as `serverEnv.NEXT_PUBLIC_*` — four call sites do today. What goes is only the object nothing could read correctly. The schema stays, with `LOG_LEVELS` lifted out of it so browser code can narrow a literal read against the same list without pulling zod in. Refs #760 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MfQ4WdiEFSEKguNxJTdBdm
The three browser call sites read their `NEXT_PUBLIC_*` value as a literal member expression. `Sentry.init` runs in a browser for the first time, and `clientLogger` stops being pinned to its 'silent' fallback. Three consequences that only surface once the DSN is truthy: `instrumentation-client.ts` gains a gate. `.env` is git-tracked and carries the real DSN, so the read alone would start sending every developer's local browser errors to the live project. A Railway deploy builds with NODE_ENV=production (#733), so that is the test. A local production build still reports — closing that needs the deployment name in the browser, which #737 inlines. `ErrorBoundary` stops calling `Sentry.init`. Two inits in one page are not additive: the second replaces the client on the current scope, so whichever ran last would decide the DSN, the environment tag and the router instrumentation. The duplicate was invisible only because neither ever ran. It now captures through the client `instrumentation-client.ts` installs, and `getClient()` is the honest test for whether anything is listening. So the volume change is browser error events only. `ErrorBoundary`'s `browserTracingIntegration` and `replayIntegration` went with its init, and the surviving init sets `tracesSampleRate: 0` — no traces, and no session replay at the 10% it would have sampled. Refs #760 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MfQ4WdiEFSEKguNxJTdBdm
The unit lane runs in node, where `process.env` is the real object, so every runtime test of this defect passes against the defective code. Only the shape of the source tells them apart — so the spec reads the AST. `public-env-substitution.spec.ts` walks the import graph from each browser entry and flags any `process.env` that is not a literal `process.env.<KEY>` read: a parse, a destructure, a computed key. Verified by reintroducing `ClientEnvSchema.parse(process.env)` and watching it fail at that line. Two controls keep it from passing vacuously: `src/lib/env/server.ts` must be flagged, since it hands zod a bare `process.env` on purpose, and the walk must reach `src/lib/env/client.ts` from an entry — the module #760 lived in. The walker moves to `tests/utils/importGraph.ts`, shared with `client-bundle-safety.spec.ts`, which keeps its own chain reporting. `ProjectSelector.tsx` is left out of the entry list: it reaches `@/lib/env/server` through the `@/plugins/access` barrel, which is the #633 rule rather than this one. Filed as #770. Refs #760 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MfQ4WdiEFSEKguNxJTdBdm
The three browser capture sites imported `@sentry/react`, the only `Sentry.init` imports `@sentry/nextjs`, and the two do not share a client. Sentry keys its global registry by SDK version — `__SENTRY__[SDK_VERSION]` in `@sentry/core/carrier.js` — and this repo resolved two versions: `@sentry/[email protected]` at the top level, and the `@sentry/[email protected]` that `@sentry/[email protected]` pins for itself. Both satisfy `^10.29.0`, so pnpm never deduped them. Measured, by setting a client through one core and reading it back through the other: nextjs `getClient()` SET, react `getClient()` undefined, carrier keys `version, 10.56.0, 10.30.0`. A `captureException` with no client returns an event id and drops the event, so this fails silently. Nothing showed, because nothing reported: with the DSN read broken neither `init` ever ran. Fixing the read alone would have left `ErrorBoundary`, `global-error.tsx` and `clientLogger` capturing into an empty carrier — #760 again, by a different route and behind a guard that looks deliberate. All three now import `@sentry/nextjs`, which is what every other Sentry call site in `src/` already does, and `@sentry/react` stops being a direct dependency. Bumping it instead would not hold: `@sentry/nextjs` pins its own copy exactly, so the two diverge again on its next bump. Refs #760 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MfQ4WdiEFSEKguNxJTdBdm
`clientLogger` took the level vocabulary from `@/lib/env/client`, whose
module scope evaluates `z.object({…})`. Nothing in this app sets
`sideEffects: false`, so a bundler keeps that body — the logger dragged zod
into every browser chunk carrying it, while its own comment claimed the
opposite.
`src/lib/env/logLevels.ts` holds the list, `ClientEnvSchema` builds its
`z.enum` from it, and the logger imports only that. Same reasoning as
`deploymentEnvironment.ts` sitting outside the barrel, plus this one.
Verified on a production build: the chunk carrying `clientLogger` no longer
reaches `lib/env/client.ts`. zod still arrives through three unrelated
chains — `lib/env/server.ts` and `lib/env/client.ts` via the access barrel
(#770), and `virtualReadinessField.ts` / `jsonField.ts` — so this narrows
one edge rather than removing zod from the admin bundle.
Refs #760
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MfQ4WdiEFSEKguNxJTdBdm
The spec argued that a hand-written file list goes stale, then opened with one: six entries, reaching 15 of the 91 `'use client'` modules in `src/`. A new client component with a bare `process.env` would have shipped green. `clientEntries()` in `tests/utils/importGraph.ts` now derives them — every `'use client'` file plus `instrumentation-client.ts` — and the scan runs once over the union, 177 files in ~450ms. It covers `global-error.tsx`, `AdminProvider`, `ProjectContext` and the public forms, none of which the list had. One exemption remains, as a named backlog entry rather than a silent skip: `lib/env/server.ts`, reachable only through the ProjectSelector chain #770 fixes. Exempting that file hides nothing — a client entry reaching server-only code is `client-bundle-safety.spec.ts`'s rule, and `@/lib/env/server` is on its list. `importsOf` also follows side-effect `import 'x'` and dynamic `import('x')` now. The old regex required a `from` clause, so a lazily imported client component was a blind spot for both specs. Three controls replace the one that broke when LOG_LEVELS moved: the entry set is non-empty and holds the files this ticket touched, the walk leaves its entries, and the scanner still flags `lib/env/server.ts`. Refs #760 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MfQ4WdiEFSEKguNxJTdBdm
`src/AGENTS.md` told contributors to add new client entry points to `client-bundle-safety.spec.ts`'s list, and named no other guard. It now also describes the substitution guard, and says its entries are derived so nobody adds to a list that does not exist. Adds the `@sentry/nextjs`-not-`@sentry/react` rule, which nothing in the repo stated and which fails silently when broken, and notes why `logLevels.ts` sits outside the `@/lib/env` barrel. Refs #760 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MfQ4WdiEFSEKguNxJTdBdm
|
🚅 Deployed to the SahajCloud-pr-771 environment in sahajcloud
1 service not affected by this PR
|
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The diff matches the ticket, and the production change is genuinely four lines. The rest earns its place. Dropping @sentry/react is what makes criterion 1 true at all, and the AST spec is the lint rule the ticket asked for.
One shape question stands out. This PR builds clientEntries() and calls a hand-written entry list the failure that let #760 ship. It then leaves client-bundle-safety.spec.ts on a four-entry hand list. That is why #770 is a ticket instead of a red test.
Criterion 2 waits on #763. Until then every preview reports tagged production. That call stays the reviewer's.
Findings
should-fix— the sibling guard keeps a hand list →importGraph.ts:126consider— a new module for five strings →logLevels.ts:13consider— the deadclientEnvis narrated seven times →client.ts:7
What was checked
- Ticket #760, the PR body, the whole diff from the attached checkout.
- Read whole:
instrumentation-client.ts, both error boundaries,clientLogger.ts, thelib/env/modules, both specs,importGraph.ts. git grepon the head: noclientEnvread, no@sentry/reactimport.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
| * `ClientEnvSchema` builds its `z.enum` from this list, so the two cannot | ||
| * drift. | ||
| */ | ||
| export const LOG_LEVELS = ['silent', 'error', 'warn', 'info', 'debug'] as const |
There was a problem hiding this comment.
Does this need its own module? It is five strings and a type, read by two files.
The stated reason is keeping zod out of the logger's chunk. The PR body then reports zod reaching the admin bundle by four other paths, which weakens it. The cheaper shape is the local literal clientLogger already had, accepting drift with a now server-only schema.
Push back if the chunk boundary is real and measured.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
There was a problem hiding this comment.
Not measured — CI does not build this app, so no chunk was inspected. The comment asserted one anyway. 83e7424 cuts it to what is checked: ./client imports zod at module scope, and nothing marks sideEffects: false.
Keeping the module for the other reason: ClientEnvSchema builds its z.enum from this list, so the logger's levels and the server's boot validation cannot diverge. A local literal accepts that silently. Whether that is worth a module is your call.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
The review asked whether `client-bundle-safety.spec.ts` could simply call `clientEntries()`, and whether the reason to hold was a red lane until #770. Measured on this branch, and the answer is neither. Matched by import specifier — which is how that guard's `SERVER_ONLY` list works — all 92 client entries find zero offenders, because the real edge is the `@/lib/env` barrel and only `@/lib/env/server` is listed. Matched by resolved file, 14 entries reach `lib/env/server.ts`, every one through `@/plugins/access -> accessConfigs -> @/lib/utilities/previewSecret -> @/lib/env`. So the swap needs that guard's matcher changed as well as 14 offenders resolved. That is a second guard's verdicts, which this ticket does not own. Record the measurement where the next reader will look, and correct `KNOWN_OFFENDERS`, which said ProjectSelector was the only path. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WmsBMsJMpAEBw3N2pfnapo
The review counted the removed `clientEnv` narrated at six sites. A comment describing a system that no longer exists ages badly, and six copies age independently. `src/AGENTS.md` keeps the whole story, including the rejected `runtimeEnv` alternative, which moved there from `lib/env/client.ts` rather than being dropped. The three code sites keep a one-line pointer and the rule they enforce. `server.ts` and `docs/environment.md` were already one line and a reader-facing reference respectively, so both stay as they are. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WmsBMsJMpAEBw3N2pfnapo
The review asked whether the chunk boundary behind this module is real and measured. It is not measured: CI does not build this app, so no chunk was inspected, and the comment asserted one as though it had been. Say what is checked instead — `./client` imports zod at module scope and nothing marks `sideEffects: false` — and lead with the reason that does not depend on a bundler at all. `ClientEnvSchema` builds its `z.enum` from this list, so the logger's vocabulary and the server's boot validation cannot diverge. A local literal accepts that divergence silently. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WmsBMsJMpAEBw3N2pfnapo
|
Three threads answered — two adopted, one left for you. Pushed 83e7424, lean gate green (1687 unit tests).
⚠ #770 is wider than it was filed as: 14 client entries reach 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Summary
process.env.NEXT_PUBLIC_SENTRY_DSNread, the only form Next substitutes.Sentry.init, and two Sentry SDK copies that do not share a client.clientEnvis deleted.NEXT_PUBLIC_LOG_LEVELnow reachesclientLogger.'use client'module and rejects anyprocess.envthat is not a literal member expression.Changes
src/lib/env/client.ts— schema only. TheclientEnvvalue is gone, along with its re-exports fromserver.tsand the barrel.src/lib/env/logLevels.ts— new, zod-free.ClientEnvSchemabuilds itsz.enumfrom it;clientLoggerimports only it.src/instrumentation-client.ts— literal DSN read, gated onNODE_ENV === 'production'.src/components/ErrorBoundary.tsx,src/app/global-error.tsx,src/lib/logger/clientLogger.ts— capture through@sentry/nextjs; the boundary no longer callsSentry.init.package.json/pnpm-lock.yaml—@sentry/reactis no longer a direct dependency.tests/utils/importGraph.ts— the walk, shared by both client-bundle guards, with a derivedclientEntries().Preview
Preview pending — Railway builds it a few minutes after this push.
Test results
pnpm lint,pnpm typecheck,pnpm typecheck:tests,pnpm test:unit(1687 passed), re-run after the review roundpublic-env-substitution(4),client-bundle-safety(5),lib-boundary— all passingpnpm build, thengrep -rl "<the DSN host>" .next/staticfinds it in a client chunk — the ticket's own check, which found nothing before this branchManual verification
production, notpr-<n>, until fix(config): tag browser errors with the deployment, not NODE_ENV #763 lands — see the first note below.inittookbrowserTracingIntegrationandreplayIntegrationwith it, and the survivinginitsetstracesSampleRate: 0.pnpm dev, throw in the admin panel, confirm nothing reaches Sentry.Notes for reviewer
Two decisions the ticket asked for.
Local development. Gated rather than dropping the DSN from the tracked
.env, because I cannot verify from here whether Railway setsNEXT_PUBLIC_SENTRY_DSNitself — if it does not, removing it from.envwould silently disable production reporting. The gate leaves one gap, stated in the code: a localpnpm build && pnpm startstill reports.Volume. Errors only, as above. If that is still more than the quota should take, the smallest lever is the
isProductiongate.This PR conflicts textually with #763 (issue #737), at both
Sentry.initsites. I left everyenvironment:line untouched so the resolution is unambiguous: take #763'sclientDeploymentEnvironment(), and take this branch's deletion of the boundary'sinitblock. Acceptance criteria 1 and 2 need both PRs — #763 supplies the deployment tag, this one makes any of it observable.⚠ #770 is wider than it was filed as, and this PR measured it. The ticket names
ProjectSelector.tsxreaching@/lib/env/serverthrough the@/plugins/accessbarrel. Measured across all 92 derived client entries, 14 reachsrc/lib/env/server.ts, every one through the same chain:@/plugins/access → accessPlugin → fieldAccess → accessConfigs → @/lib/utilities/previewSecret → @/lib/env. Not fixed here. It is the one exemption in the new spec, named in aKNOWN_OFFENDERSmap. Someone should widen #770 to match.That measurement also answers why
client-bundle-safety.spec.tskeeps its four-entry hand list. Swapping it toclientEntries()alone changes nothing: that guard matches the import specifier, and by specifier all 92 entries find zero offenders, because the real edge is the@/lib/envbarrel and only@/lib/env/serveris on itsSERVER_ONLYlist. Making the swap meaningful needs its matcher changed to resolved files as well, which alters an unrelated guard's verdicts. Recorded inimportGraph.ts.Detail
Why deleting
clientEnvrather than fixing its parse. The standard repair is to parse an enumerated object of literal member expressions (t3-env'sruntimeEnv). Reviewed and rejected: the enumeration can drift from the schema, and the drift looks exactly like working config — the same failure, re-armed. A reviewer pushed back thatsatisfies Record<keyof ClientEnv, string | undefined>closes drift at compile time, which is true and is the strongest case for keeping a value here. I went with deletion because acceptance criterion 5 asks for no client-reachable read throughclientEnv, and because nothing was lost:ServerEnvSchema extends ClientEnvSchema, so the server still validates all four variables and already reads them asserverEnv.NEXT_PUBLIC_*at four call sites. Say the word and thesatisfiesversion is a small PR. That argument now lives insrc/AGENTS.md, which is the one home for the wholeclientEnvstory — the code sites carry a one-line pointer instead of six copies.The SDK split, measured.
@sentry/core/carrier.jskeys the client registry by SDK version:__SENTRY__[SDK_VERSION]. The lockfile pinned@sentry/[email protected]at the top level while@sentry/[email protected]carries its own at 10.56.0 — both satisfy^10.29.0, so pnpm never deduped. Setting a client through one core and reading through the other givesSET/undefined, with carrier keysversion, 10.56.0, 10.30.0.captureExceptionwith no client returns an event id and drops the event. Bumping the direct dependency would not hold, since@sentry/nextjspins its copy exactly; removing it is what stops the divergence recurring.Why the new spec reads the AST. The unit lane runs in node, where
process.envis the real object, so every runtime test of this defect passes against the defective code. Only the source shape distinguishes them. A regex will not do either — the guarded modules discussprocess.envin prose. Verified by reintroducingClientEnvSchema.parse(process.env)insrc/lib/env/client.tsand watching the spec fail at that line, then restoring.Entry list. First draft hand-listed six entries reaching 15 of the repo's 91
'use client'modules; a new client component would have shipped unguarded, which is the failure the spec exists to prevent.clientEntries()derives them instead. Cost measured at ~450 ms over the 177-file union, plus ~166 ms for the onetypescriptimport; A/B on the full lane put the difference inside run-to-run noise.logLevels.tskeeps its own module, on the drift argument only. Review asked whether the chunk boundary was measured. It was not — CI does not build this app, so no chunk was inspected — and the comment has been cut back to what is checked:./clientimports zod at module scope, and nothing markssideEffects: false. What holds without a bundler is thatClientEnvSchemabuilds itsz.enumfrom this list, so the logger's levels and the server's boot validation cannot diverge. That thread is left open for the reviewer.Not done, deliberately.
tests/unit/lib-boundary.spec.tscarries a second, weaker import-regex thatimportsOfcould replace. Its regex matchesimport typeand single quotes only, so switching it would change which modules that spec counts as consumers — an unrelated guard's verdicts, out of scope here.Observed, not a defect. zod still reaches the admin bundle via
lib/env/server.tsandlib/env/client.ts(both on the #770 chain),lib/status/virtualReadinessField.ts, andfields/jsonField.ts. This branch removes onlyclientLogger's own edge.Reviewers dismissed. Using
deploymentEnvironment()for the browserenvironment:tag: it readsRAILWAY_ENVIRONMENT_NAME, which has noNEXT_PUBLIC_prefix, so Next replaces it withundefinedin the browser and the helper silently degrades toNODE_ENV— the same family of trap as #760.clientDeploymentEnvironment()in #763 exists for exactly this reason.Closes #760
🤖 Written by the sydevs autonomous loop — see what this is
🤖 Generated with Claude Code
https://claude.ai/code/session_01WmsBMsJMpAEBw3N2pfnapo