Repository navigation
fix(tanstackstart-react): Deliver the release through the page instead of the client chunks #26510
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| import { createFileRoute } from '@tanstack/react-router'; | ||
|
|
||
| export const Route = createFileRoute('/prerendered')({ | ||
| component: Prerendered, | ||
| }); | ||
|
|
||
| function Prerendered() { | ||
| return <p>Prerendered at build time</p>; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| import { expect, test } from '@playwright/test'; | ||
| import { waitForError } from '@sentry-internal/test-utils'; | ||
|
|
||
| // `release.name` in `vite.config.ts`. The client `Sentry.init` sets no release, so it takes the one the server wrote | ||
| // into the page, as the build injects the release into no client chunk. | ||
| const RELEASE = 'test-release'; | ||
|
|
||
| test('Sends client-side errors with the release of the build', async ({ page }) => { | ||
| const errorEventPromise = waitForError('tanstackstart-react', errorEvent => { | ||
| return errorEvent?.exception?.values?.[0]?.value === 'Sentry Client Test Error'; | ||
| }); | ||
|
|
||
| await page.goto('/'); | ||
| await page.locator('html[data-hydrated="true"]').waitFor(); | ||
| await page.locator('button').filter({ hasText: 'Break the client' }).click(); | ||
|
|
||
| const errorEvent = await errorEventPromise; | ||
|
|
||
| expect(errorEvent.release).toBe(RELEASE); | ||
| }); | ||
|
|
||
| test('Sends server-side errors with the release of the build', async ({ page }) => { | ||
| const errorEventPromise = waitForError('tanstackstart-react', errorEvent => { | ||
| return ( | ||
| errorEvent?.exception?.values?.[0]?.value === 'Sentry API Route Test Error' && | ||
| errorEvent?.exception?.values?.[0]?.mechanism?.type === 'auto.middleware.tanstackstart.request' | ||
| ); | ||
| }); | ||
|
|
||
| await page.goto('/'); | ||
| await page.locator('html[data-hydrated="true"]').waitFor(); | ||
| await page.locator('button').filter({ hasText: 'Break API route' }).click(); | ||
|
|
||
| const errorEvent = await errorEventPromise; | ||
|
|
||
| expect(errorEvent.release).toBe(RELEASE); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| import type { BrowserOptions as ReactBrowserOptions } from '@sentry/react'; | ||
| import { WINDOW } from '@sentry/react'; | ||
| import { RELEASE_META_TAG_NAME } from '../common/release'; | ||
|
|
||
| /** | ||
| * Takes the release from the meta tag the server writes into each page, unless `Sentry.init()` sets one. | ||
| */ | ||
| export function applyReleaseFromMetaTag(options: ReactBrowserOptions): void { | ||
| if (options.release !== undefined) { | ||
| return; | ||
| } | ||
|
|
||
| const document = WINDOW.document as typeof WINDOW.document | undefined; | ||
| const release = document?.querySelector(`meta[name="${RELEASE_META_TAG_NAME}"]`)?.getAttribute('content'); | ||
| if (release) { | ||
| options.release = release; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| /** The server writes the build's release into this meta tag, so that no content-hashed client file holds it. */ | ||
| export const RELEASE_META_TAG_NAME = 'sentry-release'; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| import { RELEASE_META_TAG_NAME } from '../common/release'; | ||
| import type { ServerEntry } from './wrapFetchWithSentry'; | ||
|
|
||
| const HEAD_CLOSING_TAG = new TextEncoder().encode('</head>'); | ||
|
|
||
| // Bytes before `</head>` stream through while we search, so this only bounds the search in pages without a | ||
| // `</head>`. Inline styles and scripts can make `<head>` large, so it leaves plenty of room for them. | ||
| const MAX_BYTES_BEFORE_HEAD_END = 1024 * 1024; | ||
|
|
||
| /** | ||
| * Writes the release at the end of the `<head>` of each page the server entry renders, where the client SDK reads it. | ||
| * The `sentryTanstackStart` Vite plugin wraps the server entry with this when it builds the app. | ||
| * | ||
| * @internal Only the code the Vite plugin generates calls this, so its parameters can change at any time. | ||
| */ | ||
| export function addReleaseMetaTag<T extends ServerEntry>(serverEntry: T, release: string): T { | ||
| if (typeof serverEntry?.fetch !== 'function') { | ||
| return serverEntry; | ||
| } | ||
|
|
||
| const metaTag = new TextEncoder().encode( | ||
| `<meta name="${RELEASE_META_TAG_NAME}" content="${escapeAttribute(release)}"/>`, | ||
| ); | ||
|
|
||
| return { | ||
| ...serverEntry, | ||
| async fetch(...args: Parameters<ServerEntry['fetch']>) { | ||
| return injectMetaTag(await serverEntry.fetch(...args), metaTag); | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| function injectMetaTag(response: Response, metaTag: Uint8Array): Response { | ||
| if ( | ||
| !response.body || | ||
| !response.headers.get('content-type')?.startsWith('text/html') || | ||
| response.headers.has('content-encoding') | ||
| ) { | ||
| return response; | ||
| } | ||
|
|
||
| let pending: Uint8Array | undefined = new Uint8Array(0); | ||
| let searchedBytes = 0; | ||
|
|
||
| // The tag goes last in `<head>`: React 18 hydrates `<head>` children in order, so a tag before the app's own | ||
| // elements would be claimed for the first of them and shift the rest. | ||
| const body = response.body.pipeThrough( | ||
| new TransformStream<Uint8Array, Uint8Array>({ | ||
| transform(chunk, controller) { | ||
| if (!pending) { | ||
| controller.enqueue(chunk); | ||
| return; | ||
| } | ||
|
|
||
| const buffered = concat(pending, chunk); | ||
| const headEnd = indexOfHeadClosingTag(buffered); | ||
| if (headEnd !== -1) { | ||
| controller.enqueue(buffered.subarray(0, headEnd)); | ||
| controller.enqueue(metaTag); | ||
| controller.enqueue(buffered.subarray(headEnd)); | ||
| pending = undefined; | ||
| return; | ||
| } | ||
|
|
||
| searchedBytes += chunk.length; | ||
| if (searchedBytes > MAX_BYTES_BEFORE_HEAD_END) { | ||
| controller.enqueue(buffered); | ||
| pending = undefined; | ||
| return; | ||
| } | ||
|
|
||
| // Hold back the bytes that could start a `</head>` split across chunks. | ||
| const heldBack = partialHeadClosingTagLength(buffered); | ||
| if (heldBack < buffered.length) { | ||
| controller.enqueue(buffered.subarray(0, buffered.length - heldBack)); | ||
| } | ||
| pending = buffered.slice(buffered.length - heldBack); | ||
| }, | ||
| flush(controller) { | ||
| if (pending?.length) { | ||
| controller.enqueue(pending); | ||
| } | ||
| }, | ||
| }), | ||
| ); | ||
|
|
||
| const headers = new Headers(response.headers); | ||
| headers.delete('content-length'); | ||
|
|
||
| return new Response(body, { status: response.status, statusText: response.statusText, headers }); | ||
| } | ||
|
|
||
| // `</head>` is ASCII, and UTF-8 never encodes an ASCII character as part of a multi-byte sequence, so matching | ||
| // bytes finds it the same way as in the decoded document. | ||
| function indexOfHeadClosingTag(bytes: Uint8Array): number { | ||
| for (let start = 0; start + HEAD_CLOSING_TAG.length <= bytes.length; start++) { | ||
| if (matchesHeadClosingTag(bytes, start, HEAD_CLOSING_TAG.length)) { | ||
| return start; | ||
| } | ||
| } | ||
| return -1; | ||
| } | ||
|
|
||
| function partialHeadClosingTagLength(bytes: Uint8Array): number { | ||
| for (let length = Math.min(HEAD_CLOSING_TAG.length - 1, bytes.length); length > 0; length--) { | ||
| if (matchesHeadClosingTag(bytes, bytes.length - length, length)) { | ||
| return length; | ||
| } | ||
| } | ||
| return 0; | ||
| } | ||
|
|
||
| function matchesHeadClosingTag(bytes: Uint8Array, start: number, length: number): boolean { | ||
| for (let i = 0; i < length; i++) { | ||
| if (toLowerCase(bytes[start + i] as number) !== HEAD_CLOSING_TAG[i]) { | ||
| return false; | ||
| } | ||
| } | ||
| return true; | ||
| } | ||
|
|
||
| function toLowerCase(byte: number): number { | ||
| return byte >= 0x41 && byte <= 0x5a ? byte + 0x20 : byte; | ||
| } | ||
|
|
||
| function concat(a: Uint8Array, b: Uint8Array): Uint8Array { | ||
| if (!a.length) { | ||
| return b; | ||
| } | ||
|
|
||
| const result = new Uint8Array(a.length + b.length); | ||
| result.set(a); | ||
| result.set(b, a.length); | ||
| return result; | ||
| } | ||
|
|
||
| function escapeAttribute(value: string): string { | ||
| return value.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>'); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import { resolveReleaseName } from '@sentry/bundler-plugins/core'; | ||
| import { stringifyForCodeInjection } from '@sentry/core'; | ||
| import type { SentryTanstackStartOptions } from './sentryTanstackStart'; | ||
|
|
||
| /** | ||
| * The release the SDK delivers at runtime instead of the bundler plugin injecting it into the startup chunks, whose | ||
| * content hashes would change with every release. Undefined when `release.inject` is `false` or there is no release. | ||
| */ | ||
| export function getRuntimeRelease(options: SentryTanstackStartOptions): string | undefined { | ||
| if (options.release?.inject === false) { | ||
| return undefined; | ||
| } | ||
|
|
||
| return resolveReleaseName(options.release?.name); | ||
| } | ||
|
|
||
| /** Sets the release where the server SDK reads it on `init`, the same way the bundler plugin does. */ | ||
| export function getServerReleaseCode(release: string): string { | ||
| return `globalThis.SENTRY_RELEASE = { id: ${stringifyForCodeInjection(release)} };\n`; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,6 +3,7 @@ import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite'; | |
| import type { Plugin } from 'vite'; | ||
| import { makeAutoInstrumentMiddlewarePlugin } from './autoInstrumentMiddleware'; | ||
| import { makeComposeNitroServiceSourceMapsPlugin, makeEnableNitroSourceMapsPlugin } from './nitroSourceMaps'; | ||
| import { getRuntimeRelease } from './release'; | ||
| import { makeRoutePatternPlugin } from './routePatterns'; | ||
| import { makeServerInstrumentationPlugin } from './serverInstrumentation'; | ||
| import { makeAddSentryVitePlugin, makeEnableSourceMapsVitePlugin } from './sourceMaps'; | ||
|
|
@@ -92,30 +93,37 @@ export function sentryTanstackStart(options: SentryTanstackStartOptions = {}): P | |
| ); | ||
| } | ||
|
|
||
| const isDevelopment = process.env.NODE_ENV === 'development'; | ||
| const release = isDevelopment ? undefined : getRuntimeRelease(options); | ||
|
|
||
| const tunnelBasePath = makeTunnelBasePathPlugin(); | ||
| const plugins: Plugin[] = [ | ||
| makeRoutePatternPlugin(), | ||
| tunnelBasePath.plugin, | ||
| makeServerEntryTunnelPlugin(tunnelRoute, tunnelBasePath.getBasePath), | ||
| makeServerEntryTunnelPlugin(tunnelRoute, tunnelBasePath.getBasePath, release), | ||
| ]; | ||
|
|
||
| if (tunnelRoute) { | ||
| plugins.push(makeTunnelRoutePlugin(tunnelRoute, options.debug)); | ||
| } | ||
|
|
||
| // only add build-time plugins in production builds | ||
| if (process.env.NODE_ENV === 'development') { | ||
| if (isDevelopment) { | ||
| return plugins; | ||
| } | ||
|
|
||
| plugins.push(makeServerInstrumentationPlugin({ debug: options.debug })); | ||
| plugins.push(makeServerInstrumentationPlugin({ debug: options.debug, release })); | ||
|
|
||
| // Runs the orchestrion code transform over the server bundle so instrumented DB drivers get | ||
| // `diagnostics_channel` publishers injected. Production-only: it force-bundles the instrumented | ||
| // (CommonJS) deps via `ssr.noExternal`, which the `vite dev` SSR module runner can't evaluate. | ||
| plugins.push(sentryOrchestrionPlugin({ buildTimeInstrumentation: options.buildTimeInstrumentation })); | ||
|
|
||
| plugins.push(...makeAddSentryVitePlugin(options), makeComposeNitroServiceSourceMapsPlugin()); | ||
| // The server entry hands the release to the SDK at runtime, so it changes no content hash of the startup chunks. | ||
| const bundlerPluginOptions = release | ||
| ? { ...options, release: { ...options.release, name: release, inject: false } } | ||
| : options; | ||
| plugins.push(...makeAddSentryVitePlugin(bundlerPluginOptions), makeComposeNitroServiceSourceMapsPlugin()); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Silent release default changeMedium Severity The bundler plugin now always gets Additional Locations (1)Triggered by project rule: PR Review Guidelines for Cursor Bot Reviewed by Cursor Bugbot for commit 7ee6e89. Configure here. |
||
|
|
||
| // middleware auto-instrumentation | ||
| if (options.autoInstrumentMiddleware !== false) { | ||
|
|
||


Uh oh!
There was an error while loading. Please reload this page.