Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
"version": "0.0.1",
"type": "module",
"scripts": {
"build": "node start-mock-sentry-server.mjs & (vite build && cp instrument.server.mjs .output/server) > .tmp_build_stdout 2> .tmp_build_stderr; BUILD_EXIT=$?; kill %1 2>/dev/null; if [ $BUILD_EXIT -ne 0 ]; then cat .tmp_build_stdout; cat .tmp_build_stderr >&2; fi; exit $BUILD_EXIT",
"build": "node start-mock-sentry-server.mjs & vite build > .tmp_build_stdout 2> .tmp_build_stderr; BUILD_EXIT=$?; kill %1 2>/dev/null; if [ $BUILD_EXIT -ne 0 ]; then cat .tmp_build_stdout; cat .tmp_build_stderr >&2; fi; exit $BUILD_EXIT",
"dev": "vite dev",
"start": "node --import ./.output/server/instrument.server.mjs .output/server/index.mjs",
"start": "node .output/server/index.mjs",
"test": "playwright test",
"clean": "npx rimraf node_modules pnpm-lock.yaml",
"test:build": "pnpm install && pnpm build",
Expand Down Expand Up @@ -36,6 +36,7 @@
"mysql": "^2.18.1"
},
"devDependencies": {
"@sentry/conventions": "0.31.0",
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@types/node": "^24.10.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { type ChildProcess, spawn } from 'node:child_process';
import { expect, test } from '@playwright/test';
import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
import { URL_FULL, URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_SERVER } from '@sentry/conventions/op';

const usesManagedTunnelRoute =
(process.env.E2E_TEST_TUNNEL_ROUTE_MODE ?? 'off') !== 'off' || process.env.E2E_TEST_CUSTOM_TUNNEL_ROUTE === '1';

test.skip(usesManagedTunnelRoute, 'Default e2e suites run only in the proxy variant');
test.skip(process.env.TEST_ENV === 'development', 'Needs the production build');

// The server that Playwright starts has already handled requests, so this test starts one of its own. Nitro imports
// the server entry on the first request, so the SDK must be initialized before that.
const PORT = 3001;

let server: ChildProcess | undefined;

// Playwright skips `finally` blocks of a test that times out.
test.afterEach(() => {
server?.kill();
});

test('Sends an http.server span for the first request of a server started without --import', async () => {
const serverProcess = spawn('node', ['.output/server/index.mjs'], {
env: { ...process.env, PORT: String(PORT) },
stdio: ['ignore', 'pipe', 'pipe'],
});
server = serverProcess;

let output = '';
await new Promise<void>((resolve, reject) => {
const onData = (data: Buffer): void => {
output += data.toString();
if (output.includes('Listening on')) {
resolve();
}
};
serverProcess.stdout.on('data', onData);
serverProcess.stderr.on('data', onData);
serverProcess.once('exit', code => reject(new Error(`Server exited with code ${code}:\n${output}`)));
});

const spanPromise = waitForStreamedSpan(
'tanstackstart-react',
span =>
!!span.is_segment &&
getSpanOp(span) === HTTP_SERVER &&
String(span.attributes[URL_FULL]?.value ?? '').includes(`localhost:${PORT}/`),
);

const response = await fetch(`http://localhost:${PORT}/`);
expect(response.status).toBe(200);

const span = await spanPromise;
expect(span.attributes[URL_PATH]?.value).toBe('/');
});
1 change: 1 addition & 0 deletions docs/repeated-init.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ When `init()` replaces a client, nothing closes the old one:
| Next.js server, Remix server, Astro server, Hono Node | Keeps the first client and returns it. Logs in debug mode only. |
| Hono Bun and Deno | Keeps the first client and returns it. Warns with its own text. |
| Nuxt server | Keeps the first client and returns it. Logs that a `--import` preload is no longer needed. |
| TanStack Start server | Keeps the first client and returns it. Logs that a `--import` preload is no longer needed. |
| Cloudflare (default) | Keeps the first client of the isolate and returns it, unless that client is closed or closing. `cacheClient: false` makes a new client on each call, with no warning. |
| Next.js edge | Warns, then replaces the client. Returns `void`. |
| Next.js server and edge in a request of `withSentry` (Cloudflare) | Creates no client, because the client of `withSentry` handles the request. Returns `undefined`. |
Expand Down
21 changes: 20 additions & 1 deletion packages/tanstackstart-react/src/server/sdk.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { applySdkMetadata } from '@sentry/core';
import { _INTERNAL_getActiveClient as getActiveClient, applySdkMetadata, consoleSandbox, debug } from '@sentry/core';
import type { NodeClient, NodeOptions } from '@sentry/node';
import {
_INTERNAL_installTunnelHooks as installTunnelHooks,
Expand All @@ -10,6 +10,25 @@ import {
* Initializes the server side of the TanStack Start React SDK
*/
export function init(options: NodeOptions): NodeClient | undefined {
// TanStack Start prerenders by running the server at build time.
if (process.env.TSS_PRERENDERING === 'true') {
debug.log('Detected a TanStack Start prerender build. Skipping Sentry server initialization.');
return undefined;
}

// The Nitro server build also runs `instrument.server` when it starts, so a `node --import` preload of it or an
// import of it in the server entry initializes the SDK a second time. The first init wins.
const activeClient = getActiveClient<NodeClient>();
if (activeClient) {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.log(
'[Sentry] The Sentry server SDK is already initialized, skipping a second initialization. With Nitro, the server build loads `instrument.server` when the server starts, so a `node --import` preload of it or an import of it in the server entry is no longer needed and can be removed.',
);
});
return activeClient;
}

const sentryOptions: NodeOptions = {
defaultIntegrations: [...getDefaultNodeIntegrations(options)],
...options,
Expand Down
3 changes: 2 additions & 1 deletion packages/tanstackstart-react/src/vite/nitroSourceMaps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,8 @@ function hasNitroSourceMapSetting(config: NitroSourceMapConfig | null | undefine
);
}

function logDebug(debug: boolean | undefined, message: string): void {
/** Logs a message when the `debug` option is enabled. */
export function logDebug(debug: boolean | undefined, message: string): void {
if (debug) {
// eslint-disable-next-line no-console
console.log(`[Sentry] ${message}`);
Expand Down
3 changes: 3 additions & 0 deletions packages/tanstackstart-react/src/vite/sentryTanstackStart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { Plugin } from 'vite';
import { makeAutoInstrumentMiddlewarePlugin } from './autoInstrumentMiddleware';
import { makeComposeNitroServiceSourceMapsPlugin, makeEnableNitroSourceMapsPlugin } from './nitroSourceMaps';
import { makeRoutePatternPlugin } from './routePatterns';
import { makeServerInstrumentationPlugin } from './serverInstrumentation';
import { makeAddSentryVitePlugin, makeEnableSourceMapsVitePlugin } from './sourceMaps';
import type { TunnelRouteOptions } from './tunnelRoute';
import { makeServerEntryTunnelPlugin, makeTunnelBasePathPlugin, makeTunnelRoutePlugin } from './tunnelRoute';
Expand Down Expand Up @@ -92,6 +93,8 @@ export function sentryTanstackStart(options: SentryTanstackStartOptions = {}): P
return plugins;
}

plugins.push(makeServerInstrumentationPlugin({ debug: options.debug }));

// 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.
Expand Down
83 changes: 83 additions & 0 deletions packages/tanstackstart-react/src/vite/serverInstrumentation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import type { Plugin } from 'vite';
import { logDebug } from './nitroSourceMaps';

const FILE_NAMES = ['instrument.server.ts', 'instrument.server.mts', 'instrument.server.js', 'instrument.server.mjs'];
const DIRECTORIES = ['', 'src'];

const NITRO_PLUGIN_ID = '#sentry/tanstackstart-server-instrumentation';

/** The parts of the Nitro instance that this plugin uses. */
type Nitro = {
options: {
dev: boolean;
node: boolean;
preset: string;
rootDir: string;
plugins: string[];
virtual: Record<string, string>;
};
};

/** Finds `instrument.server.{ts,mts,js,mjs}` in the project root or in `src/`. */
export function findServerInstrumentationFile(root: string): string | undefined {
for (const directory of DIRECTORIES) {
for (const fileName of FILE_NAMES) {
const file = path.join(root, directory, fileName);
if (fs.existsSync(file)) {
return file;
}
}
}
return undefined;
}

/**
* Bundles the server instrumentation file into the Nitro build and loads it from a Nitro plugin, which runs when the
* server starts. Nitro only imports the server entry in the first request, which is too late to trace that request.
*/
export function makeServerInstrumentationPlugin({ debug }: { debug?: boolean }): Plugin & {
nitro: { name: string; setup: (nitro: Nitro) => void };
} {
return {
name: 'sentry-tanstackstart-server-instrumentation',
apply: 'build',
nitro: {
name: 'sentry-tanstackstart-server-instrumentation',
setup(nitro) {
if (nitro.options.dev) {
return;
}

// The Node SDK must not end up in a worker or other runtime without Node.js, such as Cloudflare, where the
// Cloudflare SDK sets itself up.
if (nitro.options.node === false) {
logDebug(
debug,
`Not loading \`instrument.server\` in the Nitro server build, as the \`${nitro.options.preset}\` preset does not run Node.js.`,
);
return;
}

const file = findServerInstrumentationFile(nitro.options.rootDir);
if (!file) {
logDebug(
debug,
'Found no `instrument.server.{ts,mts,js,mjs}` in the project root or in `src/`, so the SDK does not initialize itself when the server starts.',
);
return;
}

nitro.options.virtual[NITRO_PLUGIN_ID] = `import ${JSON.stringify(file)};\nexport default () => {};\n`;
// Before the plugins of the app, so they run with an initialized SDK.
nitro.options.plugins.unshift(NITRO_PLUGIN_ID);

logDebug(
debug,
`Bundled \`${path.relative(nitro.options.rootDir, file)}\` into the Nitro server build. The SDK initializes itself when the server starts, no \`node --import\` needed.`,
);
},
},
};
}
41 changes: 41 additions & 0 deletions packages/tanstackstart-react/test/server/sdk.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as SentryNode from '@sentry/node';
import { originalConsoleMethods } from '@sentry/core';
import { SDK_VERSION } from '@sentry/node';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { init } from '../../src/server';
Expand Down Expand Up @@ -40,6 +41,46 @@ describe('TanStack Start React Server SDK', () => {
expect(init({})).not.toBeUndefined();
});

it('skips a second initialization and notifies that the `--import` preload is removable', () => {
// `consoleSandbox` calls the method recorded in `originalConsoleMethods`, so a spy on `console.log` misses it.
const logMock = vi.fn();
const originalLog = originalConsoleMethods.log;
originalConsoleMethods.log = logMock;

try {
const firstClient = init({ dsn: 'https://public@dsn.ingest.sentry.io/1337' });
const secondClient = init({ dsn: 'https://other@dsn.ingest.sentry.io/42' });

expect(nodeInit).toHaveBeenCalledTimes(1);
expect(secondClient).toBe(firstClient);
expect(SentryNode.getClient()).toBe(firstClient);
expect(logMock).toHaveBeenCalledWith(expect.stringContaining('already initialized'));
} finally {
originalConsoleMethods.log = originalLog;
}
});

it('initializes again after close()', async () => {
const firstClient = init({ dsn: 'https://public@dsn.ingest.sentry.io/1337' });
await SentryNode.close();

const secondClient = init({ dsn: 'https://public@dsn.ingest.sentry.io/1337' });

expect(nodeInit).toHaveBeenCalledTimes(2);
expect(secondClient).not.toBe(firstClient);
});

it('skips initialization while TanStack Start prerenders', () => {
vi.stubEnv('TSS_PRERENDERING', 'true');

try {
expect(init({ dsn: 'https://public@dsn.ingest.sentry.io/1337' })).toBeUndefined();
expect(nodeInit).not.toHaveBeenCalled();
} finally {
vi.unstubAllEnvs();
}
});

it('sets ignoreSpans to filter low-quality transactions', () => {
init({ dsn: 'https://public@dsn.ingest.sentry.io/1337' });

Expand Down
34 changes: 34 additions & 0 deletions packages/tanstackstart-react/test/vite/sentryTanstackStart.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Plugin } from 'vite';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { makeAutoInstrumentMiddlewarePlugin } from '../../src/vite/autoInstrumentMiddleware';
import { sentryTanstackStart, type SentryTanstackStartOptions } from '../../src/vite/sentryTanstackStart';
import { makeServerInstrumentationPlugin } from '../../src/vite/serverInstrumentation';
import { makeServerEntryTunnelPlugin, makeTunnelRoutePlugin } from '../../src/vite/tunnelRoute';

const mockSourceMapsConfigPlugin: Plugin = {
Expand Down Expand Up @@ -34,6 +35,11 @@ const mockEnableNitroSourceMapsPlugin: Plugin = {
apply: 'build',
};

const mockServerInstrumentationPlugin: Plugin = {
name: 'sentry-tanstackstart-server-instrumentation',
apply: 'build',
};

const mockMiddlewarePlugin: Plugin = {
name: 'sentry-tanstack-middleware-auto-instrument',
apply: 'build',
Expand Down Expand Up @@ -87,6 +93,10 @@ vi.mock('../../src/vite/nitroSourceMaps', () => ({
makeEnableNitroSourceMapsPlugin: vi.fn(() => mockEnableNitroSourceMapsPlugin),
}));

vi.mock('../../src/vite/serverInstrumentation', () => ({
makeServerInstrumentationPlugin: vi.fn(() => mockServerInstrumentationPlugin),
}));

vi.mock('../../src/vite/autoInstrumentMiddleware', () => ({
makeAutoInstrumentMiddlewarePlugin: vi.fn(() => mockMiddlewarePlugin),
}));
Expand Down Expand Up @@ -115,6 +125,7 @@ describe('sentryTanstackStart()', () => {
mockRoutePatternPlugin,
mockTunnelBasePathPlugin,
mockServerEntryTunnelPlugin,
mockServerInstrumentationPlugin,
mockOrchestrionPlugin,
mockSourceMapsConfigPlugin,
mockSentryVitePlugin,
Expand Down Expand Up @@ -158,6 +169,7 @@ describe('sentryTanstackStart()', () => {
mockRoutePatternPlugin,
mockTunnelBasePathPlugin,
mockServerEntryTunnelPlugin,
mockServerInstrumentationPlugin,
mockOrchestrionPlugin,
mockSourceMapsConfigPlugin,
mockSentryVitePlugin,
Expand All @@ -175,6 +187,7 @@ describe('sentryTanstackStart()', () => {
mockRoutePatternPlugin,
mockTunnelBasePathPlugin,
mockServerEntryTunnelPlugin,
mockServerInstrumentationPlugin,
mockOrchestrionPlugin,
mockSourceMapsConfigPlugin,
mockSentryVitePlugin,
Expand All @@ -192,6 +205,7 @@ describe('sentryTanstackStart()', () => {
mockRoutePatternPlugin,
mockTunnelBasePathPlugin,
mockServerEntryTunnelPlugin,
mockServerInstrumentationPlugin,
mockOrchestrionPlugin,
mockSourceMapsConfigPlugin,
mockSentryVitePlugin,
Expand All @@ -210,6 +224,7 @@ describe('sentryTanstackStart()', () => {
mockRoutePatternPlugin,
mockTunnelBasePathPlugin,
mockServerEntryTunnelPlugin,
mockServerInstrumentationPlugin,
mockOrchestrionPlugin,
mockSourceMapsConfigPlugin,
mockSentryVitePlugin,
Expand All @@ -228,6 +243,7 @@ describe('sentryTanstackStart()', () => {
mockRoutePatternPlugin,
mockTunnelBasePathPlugin,
mockServerEntryTunnelPlugin,
mockServerInstrumentationPlugin,
mockOrchestrionPlugin,
mockSourceMapsConfigPlugin,
mockSentryVitePlugin,
Expand All @@ -246,6 +262,7 @@ describe('sentryTanstackStart()', () => {
mockRoutePatternPlugin,
mockTunnelBasePathPlugin,
mockServerEntryTunnelPlugin,
mockServerInstrumentationPlugin,
mockOrchestrionPlugin,
mockSourceMapsConfigPlugin,
mockSentryVitePlugin,
Expand Down Expand Up @@ -281,6 +298,7 @@ describe('sentryTanstackStart()', () => {
mockTunnelBasePathPlugin,
mockServerEntryTunnelPlugin,
mockTunnelRoutePlugin,
mockServerInstrumentationPlugin,
mockOrchestrionPlugin,
mockSourceMapsConfigPlugin,
mockSentryVitePlugin,
Expand All @@ -305,6 +323,22 @@ describe('sentryTanstackStart()', () => {
});
});

describe('server instrumentation', () => {
it('passes debug through to the server instrumentation plugin', () => {
sentryTanstackStart({ debug: true, sourcemaps: { disable: true } });

expect(makeServerInstrumentationPlugin).toHaveBeenCalledWith({ debug: true });
});

it('does not add the server instrumentation plugin in development mode', () => {
process.env.NODE_ENV = 'development';

sentryTanstackStart({ sourcemaps: { disable: true } });

expect(makeServerInstrumentationPlugin).not.toHaveBeenCalled();
});
});

describe('orchestrion build-time instrumentation', () => {
it('adds the orchestrion plugin by default', () => {
const plugins = sentryTanstackStart({ sourcemaps: { disable: true } });
Expand Down
Loading
Loading