Skip to content

fix(studio): initialize Sentry on the TanStack build (captures were silent no-ops) - #47666

Merged
alaister merged 6 commits into
masterfrom
alaister/tanstack-sentry-init
Jul 9, 2026
Merged

alaister merged 6 commits into
masterfrom
alaister/tanstack-sentry-init

Conversation

@alaister

@alaister alaister commented Jul 7, 2026 •

Copy link
Copy Markdown
Member

Stacked on #47657 (base is alaister/tanstack-migration-fixes; retarget to master once that merges).

The TanStack runtime never ran Sentry.init — instrumentation-client.ts is a Next-convention file nothing imports under TanStack Start, so every Sentry.captureException on that build (including the routes/__root.tsx error-boundary / routerErrorComponent reports) was a silent no-op.

  • Shared config source: the entire client config moves verbatim from instrumentation-client.ts into lib/sentry-client-options.ts (buildSentryClientOptions). Both runtimes build from it, so Next and TanStack can't drift — the builds differ only in two explicit knobs.
  • TanStack init: sentry.tanstack.ts initializes @sentry/react from getRouter() (TanStack Start's real client bootstrap — the earliest point with the router instance), wiring tanstackRouterBrowserTracingIntegration(router). Window-guarded + idempotent; router.tsx is TanStack-only so the Next build is untouched. (Named without .client. — Start's import-protection fails the build for *.client.* in the server graph.)
  • Third-party error filter is intentionally Next-only: without the bundler-injected applicationKey metadata (only withSentryConfig provides it), the SDK tags every event third_party_code: true and beforeSend would drop them all — recreating the silent no-op with a DSN set. Follow-up: add @sentry/vite-plugin moduleMetadata, then enable.
  • DSN-less builds stay crash-free: vite.config.ts inlines undefined for unset NEXT_PUBLIC_SENTRY_DSN/NEXT_PUBLIC_SENTRY_ENVIRONMENT (a literal process.env.* in the bundle is the exact process is not defined class fix(studio): TanStack post-merge fixes — Monaco loader, fonts, CSP (from #46424) #47657 fixed). No-DSN → disabled client, plus the existing IS_PLATFORM/consent gates.
  • Tests: instrumentation-client.test.ts moved to lib/sentry-client-options.test.ts with all 36 assertions kept, plus integration-gating and Next/TanStack parity tests. tsc clean; full vite build --mode test passes.

Follow-up (separate): server-side Sentry for the Start handler (server.ts entry + @sentry/node-style init).

To test

  • Locally (no DSN set): load the TanStack build — no Sentry network requests, no console errors, and crucially no ReferenceError: process is not defined (the define fallback). Forcing an error must not POST to any /envelope endpoint.
  • On a preview/deploy (DSN set, telemetry consent accepted): throw a test error (e.g. crash a route component) → a POST to o…ingest.sentry.io/api/…/envelope/ fires, and the event lands in Sentry with a codeSampleRate tag and no third_party_code tag. Navigation spans named after TanStack routes appear when the 2% pageload trace samples in.
  • Next build regression check: the Next dev/preview still reports errors exactly as before (instrumentation-client.ts now builds its options from the same shared source).

Review feedback: Sentry /envelope never fires on TanStack (Joshen)

Root-caused: @sentry/core's Client.sendSession silently drops the session when the client has no release. The Next build gets a release injected by withSentryConfig (the Vercel commit SHA); the Vite build runs no Sentry bundler plugin, so it had no release → session envelopes were discarded before transport → zero /envelope traffic (errors/transactions are separate). Fix: inject release: NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA on the TanStack build (vite.config re-exposes VERCEL_GIT_COMMIT_SHA under the NEXT_PUBLIC_ name, same SHA the Next release resolves to). Also switched integrations to the function form so defaults are preserved by contract (not just by current SDK behavior). 45 unit tests green.

To test (deploys only — the SHA is unset locally, so this can't be reproduced on a local dev build): on this PR's Vercel preview with a DSN + telemetry consent, load any page and watch the Network tab for a POST to …ingest.sentry.io/…/envelope/ — a session envelope should now fire on load, matching the Next build.

Summary by CodeRabbit

  • New Features

    • Improved client-side error and performance monitoring for the Studio app across both router setups.
    • Added support for passing release/version information into monitoring data.
  • Bug Fixes

    • Reduced noisy error reporting by better filtering common browser, extension, cancellation, and load-related issues.
    • Prevented browser bundles from referencing missing environment values at runtime.
    • Made monitoring initialization safer in server-rendered and client-only environments.

@alaister
alaister requested a review from a team as a code owner July 7, 2026 01:08
@supabase

supabase Bot commented Jul 7, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@vercel

vercel Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
studio-self-hosted Ready Ready Preview, Comment Jul 8, 2026 7:05am
studio-staging Ready Ready Preview, Comment Jul 8, 2026 7:05am
5 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Jul 8, 2026 7:05am
design-system Skipped Skipped Jul 8, 2026 7:05am
docs Skipped Skipped Jul 8, 2026 7:05am
ui-library Skipped Skipped Jul 8, 2026 7:05am
zone-www-dot-com Skipped Skipped Jul 8, 2026 7:05am

Request Review

@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d85ffc32-dbc6-41b6-b119-69413d7f3283

📥 Commits

Reviewing files that changed from the base of the PR and between 378d42c and 3f65818.

📒 Files selected for processing (8)
  • apps/studio/.github/eslint-rule-baselines.json
  • apps/studio/instrumentation-client.ts
  • apps/studio/lib/sentry-client-options.test.ts
  • apps/studio/lib/sentry-client-options.ts
  • apps/studio/router.tsx
  • apps/studio/sentry.tanstack.test.ts
  • apps/studio/sentry.tanstack.ts
  • apps/studio/vite.config.ts
✅ Files skipped from review due to trivial changes (1)
  • apps/studio/.github/eslint-rule-baselines.json
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/studio/instrumentation-client.ts
  • apps/studio/sentry.tanstack.ts
  • apps/studio/router.tsx

📝 Walkthrough

Walkthrough

Sentry client configuration is extracted from Next.js instrumentation into a shared sentry-client-options.ts module, consumed by both the existing Next.js instrumentation-client and a new TanStack Start initializer (sentry.tanstack.ts) wired into the router setup, with corresponding ESLint baseline, Vite env define, and test updates.

Changes

Sentry client options extraction and consumption

Layer / File(s) Summary
Shared Sentry client options module
apps/studio/lib/sentry-client-options.ts
New module defines sampling constants, chunk-load/hCaptcha detection, exported error filter helpers, a third-party integration builder, SentryClientOptionsParams, and buildSentryClientOptions assembling DSN, tracing, integrations, allowUrls, breadcrumb sanitization, beforeSend gating/sampling, and a large ignoreErrors list.
Next.js instrumentation-client migration
apps/studio/instrumentation-client.ts, apps/studio/lib/sentry-client-options.test.ts
Replaces inline Sentry.init config with buildSentryClientOptions({ includeThirdPartyErrorFilter: true }), removing local helper functions; tests updated to import from the new module and add buildSentryClientOptions coverage.
TanStack Start Sentry initialization
apps/studio/sentry.tanstack.ts, apps/studio/sentry.tanstack.test.ts, apps/studio/router.tsx
New initSentryTanStackClient(router) is a client-only, idempotent initializer using buildSentryClientOptions with includeThirdPartyErrorFilter: false, TanStack Router tracing integration, and release from NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA; wired into getRouter(); tests cover SSR guard, init, idempotency, and integration wiring.
ESLint baseline and Vite env define updates
apps/studio/.github/eslint-rule-baselines.json, apps/studio/vite.config.ts
ESLint baseline moves the no-explicit-any suppression entry to the new file; Vite config adds VERCEL_GIT_COMMIT_SHA and ensures Sentry-related NEXT_PUBLIC_* defines fall back to 'undefined'.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
    participant Router as getRouter
    participant Init as initSentryTanStackClient
    participant Options as buildSentryClientOptions
    participant Sentry as Sentry (react)

    Router->>Init: initSentryTanStackClient(router)
    Init->>Init: check window / initialized guard
    Init->>Options: buildSentryClientOptions({includeThirdPartyErrorFilter:false, extraIntegrations, release})
    Options-->>Init: BrowserOptions
    Init->>Sentry: Sentry.init(options)
    Router->>Router: setupRouterSsrQueryIntegration
Loading

Suggested reviewers: ivasilov, awaseem

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: initializing Sentry for the TanStack Studio build.
Description check ✅ Passed It includes the bug, current behavior, new behavior, and extra context, but not in the repository’s exact template.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch alaister/tanstack-sentry-init

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results

passed  231 passed
flaky  1 flaky
skipped  5 skipped

Details

stats  237 tests across 27 suites
duration  3 minutes, 51 seconds
commit  3f65818

Flaky tests

Features › realtime-inspector.spec.ts › Realtime Inspector › Message Display › messages counter shows correct count

Skipped tests

Features › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled
Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

@coderabbitai coderabbitai Bot left a comment

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.

🧹 Nitpick comments (2)
apps/studio/lib/sentry-client-options.ts (1)

103-118: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use the typed named export here. thirdPartyErrorFilterIntegration is exposed by @sentry/react, so importing it directly removes the any cast and avoids a silent no-op if the symbol ever disappears.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/studio/lib/sentry-client-options.ts` around lines 103 - 118, The Sentry
third-party error filter setup in buildThirdPartyErrorFilterIntegration is using
an untyped access through (Sentry as any), which should be replaced with the
typed named export from `@sentry/react`. Import thirdPartyErrorFilterIntegration
directly, use that symbol in the null check and integration निर्माण, and remove
the any cast so the code fails clearly if the export is unavailable instead of
silently no-oping.
apps/studio/sentry.tanstack.ts (1)

29-42: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No test coverage for the new initializer.

initSentryTanStackClient has multiple testable branches (SSR no-op, double-init guard, options passed to Sentry.init) but there's no accompanying test file in this PR. Per the Studio Testing guidelines, extracted init/utility logic like this should get coverage (e.g., mocking @sentry/react and asserting Sentry.init is called exactly once across repeated invocations, and not called when window is undefined).

As per path instructions for apps/studio/**: "PR adds a utility function without test coverage" should be flagged.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/studio/sentry.tanstack.ts` around lines 29 - 42, The new
initSentryTanStackClient initializer lacks test coverage for its SSR no-op,
single-run guard, and Sentry.init wiring. Add a test file for the
sentry.tanstack module that mocks `@sentry/react` and verifies
initSentryTanStackClient does not initialize when window is undefined, calls
Sentry.init with the expected options when run in the browser, and only
initializes once across repeated calls by exercising the initialized guard.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@apps/studio/lib/sentry-client-options.ts`:
- Around line 103-118: The Sentry third-party error filter setup in
buildThirdPartyErrorFilterIntegration is using an untyped access through (Sentry
as any), which should be replaced with the typed named export from
`@sentry/react`. Import thirdPartyErrorFilterIntegration directly, use that symbol
in the null check and integration निर्माण, and remove the any cast so the code
fails clearly if the export is unavailable instead of silently no-oping.

In `@apps/studio/sentry.tanstack.ts`:
- Around line 29-42: The new initSentryTanStackClient initializer lacks test
coverage for its SSR no-op, single-run guard, and Sentry.init wiring. Add a test
file for the sentry.tanstack module that mocks `@sentry/react` and verifies
initSentryTanStackClient does not initialize when window is undefined, calls
Sentry.init with the expected options when run in the browser, and only
initializes once across repeated calls by exercising the initialized guard.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1708006c-f2b9-493a-a741-1f1d15286795

📥 Commits

Reviewing files that changed from the base of the PR and between 15790d2 and 378d42c.

📒 Files selected for processing (7)
  • apps/studio/.github/eslint-rule-baselines.json
  • apps/studio/instrumentation-client.ts
  • apps/studio/lib/sentry-client-options.test.ts
  • apps/studio/lib/sentry-client-options.ts
  • apps/studio/router.tsx
  • apps/studio/sentry.tanstack.ts
  • apps/studio/vite.config.ts

// convention file that nothing loads under TanStack Start. Without this init
// every `Sentry.captureException` in the TanStack runtime (including the
// globalErrorBoundary / routerErrorComponent captures in routes/__root.tsx)
// would be a silent no-op.

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.

Review context (moved out of the code comment): before this PR, nothing initialized Sentry on the TanStack build at all — so the globalErrorBoundary / routerErrorComponent captureException calls in routes/__root.tsx were silently no-oping. This file is the fix.

alaister added a commit that referenced this pull request Jul 8, 2026
…rom #46424) (#47657)

Post-merge fixes for the TanStack Start migration (#46424) — things that
broke on the TanStack build as master evolved under the migration
branches. Kept on their own branch off master rather than piling onto
the E2E-matrix PR (#47119); all land on master and cascade up to S6 +
the big PR.

Common theme: a master PR changed something the Next pipeline handles
via `next/font` / `pages/_app.tsx` / `next.config.ts`, but the
hand-rolled TanStack equivalent (`routes/__root.tsx`,
`styles/fonts.css`, `vercel.ts`) wasn't updated to match — invisible on
the Next deploy, broken only on TanStack.

---

## 1. Monaco loader path (#47182)

#47182 re-nested the served Monaco assets from a flat
`public/monaco-editor/` layout into `public/monaco-editor/vs/` and
updated `pages/_app.tsx`, but `routes/__root.tsx` still pointed
`loader.config` at the old path, so `loader.js` 404'd and **no Monaco
editor mounted anywhere in the TanStack build**. Now mirrors the Next
config (`${origin}${BASE_PATH}/monaco-editor/vs`, window-guarded for
SSR). Was failing the whole `tanstack` E2E shard on #47119.

## 2. Inter + Manrope fonts (#47306)

#47306 renamed Tailwind's sans var `--font-custom` → `--font-sans` and
added `--font-heading` (Manrope), set via `next/font` on Next.
`fonts.css` still only set the now-ignored `--font-custom`, so the body
fell back to the theme's system chain (`Circular, custom-font,
Helvetica…`) at weight 450 — that's the "Inter weights look wrong".
Manrope was missing entirely.

- Wire `--font-sans` (Inter) + `--font-heading` (Manrope) to match
`next/font`.
- **Vendor all three families** (Inter, Manrope, Source Code Pro) via
`@font-face` so nothing depends on the Google Fonts CDN — matches
`next/font` self-hosting, and (see below) `font-src` doesn't allow
`fonts.gstatic.com` anyway.

Verified in-browser: computed `body` → `Inter`, headings → `Manrope`,
all loading from local `/assets/*.woff2`.

## 3. Security headers / CSP (next.config.ts `headers()`)

The Next build sets X-Frame-Options / X-Content-Type-Options / HSTS /
**Content-Security-Policy** / Referrer-Policy via `next.config.ts`. The
TanStack build never carried these over — `vercel.ts` only set
cache-control, so **the deployed TanStack dashboard shipped with no CSP
at all**.

The TanStack deploy serves a static shell (no server to attach headers),
so they go in the Vercel config:
- `security-headers.ts` — shared source of truth, reuses `getCSP()`,
env-gated exactly like next.config.
- `vercel.ts` — apply to every response (all base-path prefixes): full
`getCSP()` + HSTS on platform.
- `scripts/serve.js` — the non-platform set (`frame-ancestors 'none'`)
for the self-hosted server.

**Tested the policy in a real browser** (temporarily enforced it on the
TanStack build via /test-supabase-local): everything passed except one
real gap — `font-src` was missing `data:`, so GraphiQL's bundled Monaco
codicon font and Stripe's payment-element fonts (both data: URIs) were
blocked (37 violations on a cold load). Added `data:` to `font-src` in
`csp.ts` → violations drop to zero, SQL editor Monaco renders clean.
That gap affects the Next build too.

---

## 4. `node:path` import crashing `/project/[ref]/merge`

Found by a full-site click-through of the TanStack build (all product
areas, ongoing — see below). `useEdgeFunctionsDiff.ts` +
`EdgeFunctionsDiffPanel.tsx` did `import { basename } from 'path'` in
client code. Webpack (Next) polyfills `path` in the browser; Vite
externalizes it, so the whole `/merge` route crashed with "Module
\"path\" has been externalized for browser compatibility". Replaced the
two `basename` call sites with a string helper. Verified in-browser:
`/merge` renders.

## 5. URL shape — Next-style search-param semantics + shim fixes

The dashboard produced malformed URLs vs the Next build (strange query
params, trailing slashes, `##` hashes). Root cause + audit verified
empirically against `@tanstack/[email protected]`; all fixed with
unit tests and browser-verified:

- **`createRouter` used TanStack's default JSON search codec** —
`?flag=true` became `?flag=%22true%22` via links, repeated
`?filter=…&filter=…` collapsed into a JSON array (breaking
multi-filter/sort table-editor URLs and the account-page round-trip,
which double-encoded), and search values arrived as numbers/booleans
where the app expects strings. New `lib/router-search-params.ts`
(Next-style: strings in, strings out, repeated keys → string[]) wired
into the router.
- **Link shim** (`compat/next/link.tsx`): `URL.hash` includes the
leading `#` while TanStack's `hash` prop adds its own → every
`href="…#section"` navigated to `##section` (hash-scroll broke);
`Object.fromEntries(searchParams)` dropped repeated query params. Both
fixed.
- **Trailing slash injected before the query** on every `?`-only
relative navigation (`/auth/providers/?provider=…`): fixed in the compat
router (prefix current pathname) and via a custom nuqs adapter
(`lib/nuqs-tanstack-adapter.tsx`) replacing the stock tanstack-router
adapter, whose `navigate({ to: '?…' })` writes hit the same TanStack
behavior (123 files use nuqs).
- **Pathname-less `router.push({ query })` leaked path params** — Next
re-consumes `ref`/`id` from `query` into the path pattern; the shim
didn't, yielding
`/editor/17597?schema=public&ref=<ref>&id=17597&filter=…` from
table-editor filter/sort, linter panels, and advisor shortcuts. The shim
now defaults the pathname to the current route pattern and backfills
omitted params.
- **Redirects dropped query + hash** (Next's `redirects()` preserves
them): `__root.tsx` `matchRedirect` and `routes/index.tsx` now carry
incoming params/hash through (consumed rule params excluded,
destination's own params win). `/?next=new-project&projectName=zzz` →
`/new/new-project?projectName=zzz`; `/sql/quickstarts?template=x#frag` →
`/sql/examples?template=x#frag`.

Browser-verified post-fix: advisors `?preset=WARN`, providers
`?provider=Google`, `?schema=auth` — all clean (no `/?`, no leaks);
repeated `filter` params survive hydration; `=true` unquoted; single
`#`.

## 6. TanStack `navigate` corrupting query values (Logs Explorer SQL
newline loss)

TanStack router-core treats a query string embedded in `navigate({ to
})` as part of the *path*: `decodePath` percent-decodes it and
`sanitizePathSegment` strips control characters, silently deleting every
`%0A`. Logs Explorer's SQL (`s` param) lost its newlines on Run/reload —
`order by timestamp desc` / `limit 5` glued into `desclimit 5`, which
then failed the LIMIT lint. Pre-existing on the TanStack build (the
stock nuqs adapter had the same shape); Next unaffected.

Fixed by never embedding query strings in `to`: the nuqs adapter and the
compat `router.push`/`replace`/`prefetch` (plus the `next/navigation`
shim) now pass search as an object through the app codec
(`splitInternalUrl` hoisted to `lib/internal-url.ts`). Guard test drives
a real `createRouter` with multi-line SQL through both producers.
Browser-verified: newlines survive the full Run → reload → re-Run cycle.

## 7. Integration overview markdown never loaded (all integrations)

`MarkdownContent` used a template-literal dynamic import
(``import(`@/static-data/integrations/${id}/overview.md`)``) — webpack
builds a context module for that, Vite can't analyze it, so every
integration detail page threw `Failed to resolve module specifier` and
rendered no overview text. Fixed with an explicit lazy registry of
literal imports (`static-data/integrations/overviews.ts`, drift-guarded
by a test) plus an `mdRawLoader()` Vite plugin mirroring next.config's
turbopack raw-loader rule. Both runtimes keep working; md stays out of
the main bundle.

## 8. GraphiQL editor never mounted (`exports is not defined`)

Our `umdAmdShortCircuit()` Vite plugin (which disarms Monaco's global
AMD loader for deps like papaparse) rewrote `typeof define ===
'function' && define.amd` to `false` inside `monaco-editor`'s bundled
copy of marked — whose UMD relies on its own *local* `define` shim — so
the whole optimized monaco chunk failed to evaluate and GraphiQL's
editor pane stayed blank. The check now only short-circuits when
`define` is the global AMD loader. Browser-verified: all four GraphiQL
Monaco panes mount, queries execute. (Known follow-up: GraphiQL's Monaco
workers fall back to the main thread under Vite — functional, worker
wiring is Next-specific `setup-workers/webpack`.)

## 9. `@sentry/nextjs` bundling Next internals — built TanStack bundle
crashed (caught by E2E)

The E2E suite against the **built** TanStack bundle (not the dev server)
found lazy chunks like `table-editor-*.js` dead on arrival:
`@sentry/nextjs` (imported by ~25 client files) drags in
`next/dist/shared/lib/constants`, whose module scope evaluates
`process?.features?.typescript` — optional chaining doesn't guard an
undeclared `process` in the browser, so the whole chunk failed at load
with `ReferenceError: process is not defined`. Dev shims `process`,
which is why weeks of dev-server testing never saw it.

Fixed by aliasing `@sentry/nextjs` → `compat/sentry-nextjs.ts`
(re-exports `@sentry/react`, same deduped 10.59.0, plus explicit
stand-ins for the three Next-only APIs) in the Vite build only.
Verified: fresh build has zero Next-internals markers in any chunk;
table editor loads clean; full E2E suite run against the built bundle.

Note for the stack: `alaister/tanstack-start` / the E2E-matrix branch
already carried a different fix for the same crash (a `next/constants`
shim) that never made it to master — the cherry-pick onto those branches
keeps **both** (the shim covers any other transitive importer; the alias
keeps Next internals out of the client bundle entirely).

**Follow-up found while fixing:** Sentry is never *initialized* in the
TanStack runtime — `instrumentation-client.ts` /
`sentry.server.config.ts` are Next-convention files nothing imports
under TanStack, so `captureException` calls are silent no-ops. Needs an
`@sentry/react` init (+ `tanstackRouterBrowserTracingIntegration`) wired
into the TanStack client entry as its own PR.

## 10. GraphiQL Monaco workers + edge-function Deno typings (Vite-only
gaps)

- **GraphiQL's Monaco workers ran on the main thread** under Vite
("Could not create web worker(s)…" — `setup-workers/webpack`'s `new
URL(...)` form isn't rewritten by Vite). A `graphiqlViteWorkers()`
plugin resolves the import to graphiql's own `setup-workers/vite`
variant for client builds (SSR untouched, Next untouched); the
setup-workers chain is `optimizeDeps.exclude`d because the Rolldown
optimizer can't load `?worker` ids.
- **Edge-function editors silently lost their Deno typings** —
`AIEditor` loaded `public/deno/*.d.ts` via `/* @vite-ignore */` imports
that always failed at runtime under Vite. The `.md` raw loader is
generalized into `rawTextLoader` (exact-path allowlist for the two
typings files, served as virtual string modules so the dep scanner never
parses `.d.ts` syntax), and the imports are now static-analyzable
literals that both bundlers handle (turbopack's raw-loader rules match
them on the Next side).

## Split out for reviewability

App-level fixes that reproduce on the Next build too (DOM-nesting
hydration errors, the ghost deleted-snippet nav, the recurring pg-meta
`migrations` 400) moved to their own PR: #47667. Sentry initialization
for the TanStack runtime (captures were silent no-ops) is #47666,
stacked on this PR.

## Full-site test campaign

Drove every dashboard product area on the local TanStack build
(Playwright, human-style) hunting migration regressions:
redirects/404/catch-alls, org, account, project home/branches/merge,
table editor CRUD, SQL editor (Monaco/run/save/templates/AI), all
database pages, all auth pages, storage CRUD, edge functions + realtime,
logs/observability, advisors, settings, integrations hub incl. nested
routes, global UI (palette/connect/switchers/theme/fonts), and a
cross-cutting sweep (document titles, back/forward chain, hard-refresh
hydration on deep URLs, trailing-slash active state). Every failure
found is fixed above and re-verified in-browser; remaining console
quirks were cross-checked against the deployed Next build and are
pre-existing (tracked separately).

## To test

Most fixes are already browser-verified + covered by unit tests and the
self-hosted E2E suite; the last two landed after the final browser pass
and still need an in-browser check:

1. **GraphiQL Monaco workers** — restart the dev server (clear
`apps/studio/node_modules/.vite` once first — the optimizer cache may
hold a stale prebundle of the worker chain). Open
`/project/<ref>/integrations/graphiql/graphiql` with the console open:
the `Could not create web worker(s). Falling back to loading web worker
code in main thread` warning must be gone, and DevTools → Sources →
Threads shows the three workers (json, editor, graphql). Autocomplete in
the query editor stays responsive.
2. **Edge-function Deno typings** — `/project/<ref>/functions/new`: no
"Failed to load … typings" console error, and typing `Deno.` in the
editor offers typed completions (e.g. `Deno.env`).

Spot-checks for the rest (all previously verified):
- `/project/<ref>/merge` renders (no "Module path" crash).
- Multi-line SQL in Logs Explorer survives Run → reload (no `desclimit`
gluing, no LIMIT-lint false failure); `s` param keeps `%0A`.
- `/auth/providers` → open a provider → `?provider=…` with no trailing
slash before `?`; table-editor filter/sort URLs carry no leaked
`ref`/`id` params; `/?next=new-project&projectName=x` lands on
`/new/new-project?projectName=x`.
- Integration detail pages (cron/queues/vault/data_api) show their
overview prose; GraphiQL query editor mounts.
- Built bundle (`MODE=test vite build` + `start:tanstack`): table editor
loads with no `process is not defined`.
- `curl -sI` any page on a platform deploy: `X-Content-Type-Options:
nosniff` (was the invalid `no-sniff`).


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Centralized integration overview markdown loading with registry-based
lookup.
* Improved Monaco loading/asset path handling for smoother editor
startup.
* **Bug Fixes**
* Next-style navigation/search handling now preserves pathname, hash,
repeated query keys, and special characters (including newlines).
* Redirects now reliably carry over query and hash with correct
precedence.
* **Security/Configuration**
* Updated CSP font sourcing and unified security headers delivery across
environments; conditional HSTS behavior.
* Refreshed font CSS variables and font-face definitions to match the
theme.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->


---

### Review feedback: non-prod favicon (Joshen)

The TanStack `__root.tsx` hardcoded the prod favicon; local + hosted
staging now use the white staging favicon (`/favicon/staging`), matching
what `pages/_app.tsx` passes to `MetaFaviconsPagesRouter` for non-prod.
Rather than pull the pages-router component into the TanStack head, it
reuses the same synchronous `NEXT_PUBLIC_ENVIRONMENT` signal the file
already uses for `IS_DEV_TOOLBAR_ENABLED` (the `head()` route option
isn't a React component, so it can't run `_app`'s async CLI check — but
the env signal covers the reported local/staging case).

---------

Co-authored-by: Alaister Young <[email protected]>
Co-authored-by: Joshen Lim <[email protected]>
Base automatically changed from alaister/tanstack-migration-fixes to master July 8, 2026 06:53
@alaister
alaister requested a review from a team as a code owner July 8, 2026 06:53
alaister added 6 commits July 8, 2026 15:01
…ilent no-ops)

Nothing loads Next's convention files (instrumentation-client.ts) under
TanStack Start, so the TanStack runtime never called Sentry.init — every
Sentry.captureException there (including the globalErrorBoundary and
routerErrorComponent captures in routes/__root.tsx) was a silent no-op.

- Extract the entire client config (DSN/environment envs, sample rates,
  integrations, allowUrls, beforeBreadcrumb, beforeSend filters,
  ignoreErrors) from instrumentation-client.ts into a shared builder,
  lib/sentry-client-options.ts, so the two runtimes cannot drift.
  instrumentation-client.ts now just calls Sentry.init with it.
- Add sentry.tanstack.ts, called from getRouter() (router.tsx) — the
  earliest point with access to the router instance — wiring
  tanstackRouterBrowserTracingIntegration for pageload/navigation spans.
  Guarded to the browser (getRouter also runs during SSR/prerender) and
  idempotent. Not named *.client.* on purpose: TanStack Start's
  import-protection denies such modules in the server bundle.
- thirdPartyErrorFilterIntegration stays Next-only: the Vite build runs no
  Sentry bundler plugin, so frames carry no applicationKey metadata and the
  integration would tag EVERY event third_party_code=true — beforeSend
  would then drop all non-error-boundary events. Follow-up: annotate via
  @sentry/vite-plugin moduleMetadata, then enable it.
- vite.config.ts: inline `undefined` for unset NEXT_PUBLIC_SENTRY_DSN /
  NEXT_PUBLIC_SENTRY_ENVIRONMENT so self-hosted builds without a DSN don't
  ship a literal `process.env.*` (undeclared `process` throws in the
  browser). With no DSN the init is a clean no-op.
- Move instrumentation-client.test.ts to lib/sentry-client-options.test.ts
  and add coverage for the integration gating and Next/TanStack parity.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
- Use the typed named thirdPartyErrorFilterIntegration export from
  @sentry/react instead of an untyped (Sentry as any) lookup, so the
  build fails loudly if the export ever disappears (verified present in
  @sentry/react 10.59.0).
- Add sentry.tanstack.test.ts covering the initializer: no init during
  SSR (no window), browser init with the shared options and DSN gating,
  exactly one init across repeated calls (including SSR-then-browser
  ordering), and the TanStack Router tracing integration wiring with the
  third-party filter left off.
- Rename the thirdPartyErrorFilter option to includeThirdPartyErrorFilter
  and the module flag to isInitialized per studio boolean-naming
  conventions.
- Ratchet the no-explicit-any baseline down for the removed cast.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
On the TanStack build Sentry initialized but never sent any /envelope
requests, while the Next build sends a session envelope on every page
load.

Root cause: the SDK silently drops session envelopes when the client
has no release — Client.sendSession in @sentry/[email protected] early-
returns when neither the session nor the client options carry one. The
Next build gets its release injected into the bundle at build time by
withSentryConfig (SENTRY_RELEASE ?? the Vercel commit SHA); the Vite
build runs no Sentry bundler plugin, so its client had no release and
browserSessionIntegration's captured sessions were discarded before
reaching the transport. Fix: vite.config.ts re-exposes
VERCEL_GIT_COMMIT_SHA as NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA (with an
inlined-undefined fallback off Vercel) and sentry.tanstack.ts passes it
as the release — the same value the Next build's release resolves to.
The shared builder only emits the release key when one is provided:
a release: undefined entry would override the Next build's injected
release, since @sentry/nextjs spreads user options last.

Also switch the shared integrations option from a plain array to the
documented function form ((defaults) => [...defaults, ...ours]). At
@sentry/[email protected] the array form already merged with the default
integrations, so this is behavior-preserving — but the function form
states the add-don't-replace intent explicitly and is guaranteed by the
SDK contract rather than by getIntegrationsToSetup's merge behavior.
Tests now invoke the function with representative defaults
(BrowserSession, GlobalHandlers) and assert they survive the merge on
both builds.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
No code change — Vercel was switched to build this branch with TanStack,
so this empty commit kicks a fresh preview build to confirm the session
/envelope fix (release injection) fires end-to-end on a deploy.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
Real file change to trigger the TanStack Vercel build (the prior empty
commit was skipped by Vercel's change detection) so the session /envelope
fix can be confirmed on the preview.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
@alaister
alaister force-pushed the alaister/tanstack-sentry-init branch from d0155f6 to 3f65818 Compare July 8, 2026 07:02
alaister added a commit that referenced this pull request Jul 8, 2026
…n on the TanStack build

Hybrid Sentry setup for the TanStack Start build:

- Server: use the unified `@sentry/tanstackstart-react` SDK (pinned to
  10.59.0 to share the single @sentry/core hub) for server instrumentation.
  `sentryGlobalRequestMiddleware` + `sentryGlobalFunctionMiddleware` wrap the
  whole request / server-function lifecycle — capturing request- and
  function-scoped errors, including ones downstream code swallows into a 500
  that the manual `@sentry/nextjs` path never sees — and `wrapFetchWithSentry`
  wraps the fetch handler on both Vercel (api/server.js) and self-hosted
  (scripts/serve.js). `instrument.server.mjs` mirrors sentry.server.config.ts
  (dsn/environment/tracesSampleRate/ignoreErrors) + release for source maps.
  `sentryTanstackStart()` runs last in vite.config for source-map/release
  upload (skipped gracefully without SENTRY_AUTH_TOKEN); middleware auto-wrap
  is disabled since start.ts wires the middlewares explicitly.

- Client: stays on `@sentry/react` (via #47666's `@sentry/nextjs` → compat
  shim alias). The unified SDK's browser `tanstackRouterBrowserTracingIntegration`
  is a no-op stub (returns undefined → TypeError), so the client keeps the
  verified `@sentry/react` integration. The server files import
  `@sentry/tanstackstart-react` directly — they only run in the SSR/Node
  bundle, so the broken browser export never loads. Verified the server SDK
  (`@sentry/node`, global middlewares) does not leak into the client bundle.

- Next.js build path (instrumentation.ts / sentry.server.config.ts /
  next.config.ts) is untouched. Supersedes the manual `@sentry/node` server
  wrapper.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
@alaister
alaister merged commit 74bc0a8 into master Jul 9, 2026
34 checks passed
@alaister
alaister deleted the alaister/tanstack-sentry-init branch July 9, 2026 10:41
@github-actions

github-actions Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1783593832)

Score Average Improvements Regressions
Knowledge Usage 97.4% (+3pp) 2 🟢 1 🔴
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Tool Usage 76.5% (+4pp) 1 🟢 -
Time_to_first_token 2.8tok (-0.16tok) 21 🟢 8 🔴
Llm_calls 3.29 (+0.43) 19 🟢 5 🔴
Tool_calls 3.16 (+0.28) 15 🟢 8 🔴
Errors 5.29 (+0.07) 1 🟢 6 🔴
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 25817.38tok (+1941.93tok) 10 🟢 16 🔴
Prompt_cached_tokens 7838.9tok (+512tok) 16 🟢 8 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 596.21tok (+2.21tok) 12 🟢 17 🔴
Completion_reasoning_tokens 97.95tok (+6.79tok) 12 🟢 13 🔴
Total_tokens 26413.59tok (+1944.14tok) 10 🟢 19 🔴
Estimated_cost 0$ (+0$) 8 🟢 17 🔴
Duration 17.26s (+0.26s) 11 🟢 18 🔴
Llm_duration 12.73s (+1.53s) 7 🟢 22 🔴

alaister added a commit that referenced this pull request Jul 9, 2026
…n on the TanStack build

Hybrid Sentry setup for the TanStack Start build:

- Server: use the unified `@sentry/tanstackstart-react` SDK (pinned to
  10.59.0 to share the single @sentry/core hub) for server instrumentation.
  `sentryGlobalRequestMiddleware` + `sentryGlobalFunctionMiddleware` wrap the
  whole request / server-function lifecycle — capturing request- and
  function-scoped errors, including ones downstream code swallows into a 500
  that the manual `@sentry/nextjs` path never sees — and `wrapFetchWithSentry`
  wraps the fetch handler on both Vercel (api/server.js) and self-hosted
  (scripts/serve.js). `instrument.server.mjs` mirrors sentry.server.config.ts
  (dsn/environment/tracesSampleRate/ignoreErrors) + release for source maps.
  `sentryTanstackStart()` runs last in vite.config for source-map/release
  upload (skipped gracefully without SENTRY_AUTH_TOKEN); middleware auto-wrap
  is disabled since start.ts wires the middlewares explicitly.

- Client: stays on `@sentry/react` (via #47666's `@sentry/nextjs` → compat
  shim alias). The unified SDK's browser `tanstackRouterBrowserTracingIntegration`
  is a no-op stub (returns undefined → TypeError), so the client keeps the
  verified `@sentry/react` integration. The server files import
  `@sentry/tanstackstart-react` directly — they only run in the SSR/Node
  bundle, so the broken browser export never loads. Verified the server SDK
  (`@sentry/node`, global middlewares) does not leak into the client bundle.

- Next.js build path (instrumentation.ts / sentry.server.config.ts /
  next.config.ts) is untouched. Supersedes the manual `@sentry/node` server
  wrapper.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
alaister added a commit that referenced this pull request Jul 10, 2026
…n on the TanStack build (#47724)

Stacked on #47666 (base `alaister/tanstack-sentry-init`; retarget to
`master` when that merges). **Supersedes #47721** (the manual
`@sentry/node` wrapper). Client stays on #47666's `@sentry/react` setup.

Adopts the official `@sentry/tanstackstart-react` SDK **on the server
only**, after a spike (#47723) evaluating the full unified client+server
SDK. The spike found the SDK's **browser**
`tanstackRouterBrowserTracingIntegration` is a broken no-op stub at
10.59.0/10.64.0 — so the client stays on `@sentry/react` (whose
equivalent integration is a real, working implementation, already
shipped in #47666). The **server** exports, however, are a clear upgrade
and slot in cleanly.

### What this adds (server-side, TanStack build only)
- **`instrument.server.mjs`** — `Sentry.init` from
`@sentry/tanstackstart-react`, mirroring `sentry.server.config.ts` +
`release: VERCEL_GIT_COMMIT_SHA`.
- **`start.ts`** — `sentryGlobalRequestMiddleware` +
`sentryGlobalFunctionMiddleware` at the front of the existing
`createStart(...)` middleware. **This is the win**: it captures request-
and server-function errors *including the ones swallowed into 500s* —
the exact class the manual wrapper (and the Next server SDK) miss.
- **`api/server.js` / `scripts/serve.js`** — gated
(`STUDIO_FRAMEWORK==='tanstack'`) instrument init +
`wrapFetchWithSentry` on the handler.
- **`vite.config.ts`** — `sentryTanstackStart({ …,
autoInstrumentMiddleware: false })` as the last plugin: source-map
upload + release injection (skips gracefully without an auth token).
Middleware is wired explicitly rather than via the plugin's
string-rewrite.

### Guarantees
- **Client untouched** — the `@sentry/nextjs`→`@sentry/react` alias and
#47666's client init are unchanged.
- **Next untouched** — `instrumentation.ts` / `sentry.server.config.ts`
etc. stay as-is; all new code is TanStack-gated.
- **No server SDK in the client bundle** — verified after build: no
`@sentry/node` / server middleware / `wrapFetchWithSentry` in
`dist/client/assets` (`start.ts`'s server import is tree-shaken out).

### Verified
TanStack build exit 0 (past `assertNoChunkCycles`), post-build server
boot served `/api/get-utc-time → 200`, `tsc --noEmit` clean,
prettier/eslint clean. Node smoke: no-DSN init is a clean no-op; wrapped
handler returns 200.

### To test (deploy with a server DSN)
Throw a server error from an `/api/*` route (or a `/_serverFn/*`) —
including one that gets turned into a 500 without rethrowing — and
confirm a server event in Sentry with `release` = the deploy SHA.
Compared to #47721, the swallowed-500 case should now be captured via
the middleware.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added Sentry integration for the Studio app’s TanStack Start runtime,
including request and server-function instrumentation.
* Wrapped server request handling to capture errors reliably, with
tracing enabled.
* Updated build tooling to conditionally upload source maps when
credentials are present.

* **Bug Fixes**
* Improved resilience by safely falling back to a no-op Sentry setup if
instrumentation cannot be loaded.
* Ensured existing request protection remains enabled while adding
observability middleware.

* **Chores / Config**
* Added `SKIP_ASSET_UPLOAD` to the build environment list to control
cache/build behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <[email protected]>
Co-authored-by: Joshen Lim <[email protected]>
@alaister alaister mentioned this pull request Jul 10, 2026
6 tasks
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.

2 participants