Skip to content

feat(studio): report server-side errors to Sentry on the TanStack build - #47721

Closed
alaister wants to merge 1 commit into
alaister/tanstack-sentry-initfrom
alaister/tanstack-server-sentry
Closed

alaister wants to merge 1 commit into
alaister/tanstack-sentry-initfrom
alaister/tanstack-server-sentry

Conversation

@alaister

@alaister alaister commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

Stacked on #47666 (base is alaister/tanstack-sentry-init; retarget to master once that merges). Grouped with the client Sentry work for review — code-wise it's independent (different files).

Follow-up to #47666, which initialized Sentry on the TanStack client. The TanStack server path had no Sentry at all: api/server.js (Vercel) and scripts/serve.js (self-hosted) both just import the built dist/server/server.js { fetch } handler, so SSR errors, the shimmed /api/* handlers, and /_serverFn/* went completely unreported — whereas the Next build instruments the server via instrumentation.ts → sentry.server.config.ts.

  • New apps/studio/scripts/lib/sentry-server.js (plain ESM — the server entries run un-transpiled under Node): initServerSentry() inits @sentry/node mirroring sentry.server.config.ts (DSN, environment, tracesSampleRate, the same ignoreErrors), plus release: VERCEL_GIT_COMMIT_SHA (matches the client release fix so client + server events share a release). No-op without a DSN; idempotent. wrapFetchHandler() runs each request in a Sentry isolation scope and, on a thrown error, captureException → await Sentry.flush(2000) (mandatory on serverless — Vercel freezes the function after the response) → rethrow so the platform still returns its 500.
  • Wired into api/server.js and scripts/serve.js, gated to STUDIO_FRAMEWORK === 'tanstack' so the Next build — and api/server.js's inert Next-mode path — never load @sentry/node, never init, and never double-report.
  • Untouched: sentry.server.config.ts, sentry.edge.config.ts, instrumentation.ts, next.config.ts, and all client Sentry files. Both runtimes keep working from the same tree.
  • @sentry/[email protected] added (matches the rest of the Sentry packages; already in the tree transitively, so a ~minimal lockfile delta).

Known limitation: TanStack Start / the apiWrapper shim swallow some errors into 500 responses without throwing — those don't reach the wrapper. SSR render errors are still captured client-side by the __root error boundary; a fuller server-error hook is a follow-up.

To test (deploy with a server DSN set)

  1. Hit an /api/* route (or /_serverFn/*) that throws server-side on the TanStack preview → a server event arrives in Sentry with release = the deploy's commit SHA (matching client events).
  2. A Next.js production deploy is unchanged — server errors still report via instrumentation.ts only, no duplicates.

Summary by CodeRabbit

  • New Features

    • Improved server-side error reporting for Studio requests, helping capture and surface runtime issues more reliably.
    • Added a preflight step for eval workflows to support a smoother run process.
  • Bug Fixes

    • Preserved the existing fallback behavior for non-TanStack environments while making request handling more consistent.

The TanStack server path (api/server.js on Vercel, scripts/serve.js
self-hosted) ran no Sentry, so SSR / shimmed /api/* / server-function
errors went unreported — while the Next build instruments the server via
instrumentation.ts + sentry.server.config.ts. Add a plain-ESM
scripts/lib/sentry-server.js (initServerSentry + wrapFetchHandler using
@sentry/node), wired into both entries and GATED to STUDIO_FRAMEWORK=
tanstack so the Next build (and api/server.js's inert Next-mode path) is
untouched and never double-inits. release mirrors the client fix
(VERCEL_GIT_COMMIT_SHA). Next's server config files are left as-is.

Known limitation: TanStack/apiWrapper swallow some errors into 500s
without throwing; those don't reach the wrapper (SSR render errors are
still captured client-side by the __root boundary) — a fuller server
capture hook is a follow-up.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
@alaister
alaister requested a review from a team as a code owner July 8, 2026 04:33
@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2f7d8d59-87cd-4214-81e7-5e81f744103d

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • ✅ Review completed - (🔄 Check again to review again)
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch alaister/tanstack-server-sentry

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.

@supabase

supabase Bot commented Jul 8, 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 8, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
design-system Ready Ready Preview, Comment Jul 8, 2026 4:40am
docs Ready Ready Preview, Comment, Open in v0 Jul 8, 2026 4:40am
studio-self-hosted Ready Ready Preview, Comment Jul 8, 2026 4:40am
studio-staging Ready Ready Preview, Comment Jul 8, 2026 4:40am
ui-library Ready Ready Preview, Comment Jul 8, 2026 4:40am
zone-www-dot-com Ready Ready Preview, Comment, Open in v0 Jul 8, 2026 4:40am

Request Review

@github-actions

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results

passed  227 passed
flaky  4 flaky
skipped  5 skipped

Details

stats  236 tests across 26 suites
duration  4 minutes, 30 seconds
commit  98bef48

Flaky tests

Features › filter-bar.spec.ts › Filter Bar › Boolean Column Filters › filtering by false shows only false rows
Features › realtime-inspector.spec.ts › Realtime Inspector › Broadcast Messages › broadcast modal validates JSON payload
Features › realtime-inspector.spec.ts › Realtime Inspector › Message Display › messages counter shows correct count
Features › sql-editor.spec.ts › SQL Editor › should check if SQL editor is working as expected

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.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/studio/scripts/serve.js (1)

175-175: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Restore baseline security headers in apps/studio/scripts/serve.js. The standalone self-hosted server only sets content/cache headers and forwards SSR headers, so it should also apply the same X-Frame-Options, X-Content-Type-Options, Content-Security-Policy, and Referrer-Policy defaults.

🤖 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/scripts/serve.js` at line 175, The standalone server setup in
serve.js is missing the baseline security headers, so update the
request/response handling around the server bootstrap to apply the same defaults
for X-Frame-Options, X-Content-Type-Options, Content-Security-Policy, and
Referrer-Policy in addition to the existing content/cache and SSR headers. Use
the existing server initialization logic near the port configuration and the
header forwarding path to ensure these headers are always set for self-hosted
responses.
🤖 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.

Inline comments:
In `@apps/studio/scripts/lib/sentry-server.js`:
- Line 94: The request context in the Sentry setup currently records the full
URL, which can leak query parameters and sensitive values. Update the
request_info context in the Sentry server helper so it uses only the pathname or
a scrubbed URL without the query string, and keep the change localized around
the existing scope.setContext call in the Sentry request handling flow.

---

Outside diff comments:
In `@apps/studio/scripts/serve.js`:
- Line 175: The standalone server setup in serve.js is missing the baseline
security headers, so update the request/response handling around the server
bootstrap to apply the same defaults for X-Frame-Options,
X-Content-Type-Options, Content-Security-Policy, and Referrer-Policy in addition
to the existing content/cache and SSR headers. Use the existing server
initialization logic near the port configuration and the header forwarding path
to ensure these headers are always set for self-hosted responses.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ce8f300e-3e36-4bd0-aacf-6ff90622750f

📥 Commits

Reviewing files that changed from the base of the PR and between d0155f6 and 98bef48.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !pnpm-lock.yaml
📒 Files selected for processing (5)
  • apps/studio/api/server.js
  • apps/studio/package.json
  • apps/studio/scripts/lib/sentry-server.js
  • apps/studio/scripts/serve.js
  • pnpm-workspace.yaml

try {
return await handler.fetch(request)
} catch (err) {
scope.setContext('request_info', { method: request.method, url: request.url })

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Avoid sending full request URLs to Sentry.

Line 94 includes the full URL, including query parameters. Error-reporting contexts can retain tokens, OAuth codes, or user-entered values; prefer path-only context or explicitly scrub the query string.

Suggested change
-          scope.setContext('request_info', { method: request.method, url: request.url })
+          const requestUrl = new URL(request.url)
+          scope.setContext('request_info', {
+            method: request.method,
+            path: requestUrl.pathname,
+          })
🤖 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/scripts/lib/sentry-server.js` at line 94, The request context in
the Sentry setup currently records the full URL, which can leak query parameters
and sensitive values. Update the request_info context in the Sentry server
helper so it uses only the pathname or a scrubbed URL without the query string,
and keep the change localized around the existing scope.setContext call in the
Sentry request handling flow.

@alaister

alaister commented Jul 8, 2026

Copy link
Copy Markdown
Member Author

Superseded by #47724, which does the same server-side error reporting via the official @sentry/tanstackstart-react middleware instead of a hand-rolled @sentry/node wrapper — and additionally captures request/function errors that get swallowed into 500s (which this manual wrapper couldn't see). Closing in favour of #47724.

@alaister alaister closed this Jul 8, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant