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 @@ -10,6 +10,7 @@ module.exports = withSentryConfig(nextConfig, {
silent: true,
release: {
name: 'foobar123',
inject: !process.env.E2E_RELEASE_NOT_INJECTED,
},
_experimental: {
vercelCronsMonitoring: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
},
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz"
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
"@sentry/conventions": "0.33.0"
},
"sentryTest": {
"optionalVariants": [
Expand All @@ -52,6 +53,11 @@
"build-command": "pnpm install",
"label": "nextjs-15 (development)",
"assert-command": "pnpm test:dev"
},
{
"build-command": "E2E_RELEASE_NOT_INJECTED=1 pnpm test:build",
"label": "nextjs-15 (release not injected, production)",
"assert-command": "E2E_RELEASE_NOT_INJECTED=1 pnpm test:prod"
}
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved
]
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { expect, test } from '@playwright/test';
import { getSpanOp, waitForError, waitForStreamedSpan } from '@sentry-internal/test-utils';
import { HTTP_SERVER, PAGELOAD } from '@sentry/conventions/op';

test('sends App Router server and pageload spans with the release', async ({ page }) => {
const serverSpanPromise = waitForStreamedSpan('nextjs-15', span => {
return span.name === 'GET /pageload-tracing' && getSpanOp(span) === HTTP_SERVER && span.is_segment;
});
const pageloadSpanPromise = waitForStreamedSpan('nextjs-15', span => {
return span.name === '/pageload-tracing' && getSpanOp(span) === PAGELOAD && span.is_segment;
});

await page.goto('/pageload-tracing');

const [serverSpan, pageloadSpan] = await Promise.all([serverSpanPromise, pageloadSpanPromise]);
expect(serverSpan.attributes['sentry.release']?.value).toBe('foobar123');
expect(pageloadSpan.attributes['sentry.release']?.value).toBe('foobar123');
});

test('sends Pages Router client errors with the release', async ({ page }) => {
const errorPromise = waitForError('nextjs-15', errorEvent => {
return errorEvent.exception?.values?.[0]?.value === 'click error';
});

await page.goto('/42/click-error');
await page.click('#error-button');

expect((await errorPromise).release).toBe('foobar123');
});

test('keeps the release out of the client bundles with `release.inject: false`', async ({ page }) => {
test.skip(!process.env.E2E_RELEASE_NOT_INJECTED, 'Only for builds with `release.inject: false`');

const scriptBodies: Promise<string>[] = [];
page.on('response', response => {
if (response.url().includes('/_next/static/') && response.url().endsWith('.js')) {
scriptBodies.push(response.text());
}
});

const documentResponse = await page.goto('/42/click-error');
await page.waitForLoadState('networkidle');

expect(await documentResponse?.headerValue('server-timing')).toContain('sentry-release;desc="foobar123"');
expect(scriptBodies.length).toBeGreaterThan(0);
expect((await Promise.all(scriptBodies)).filter(body => body.includes('foobar123'))).toEqual([]);
});
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export default withSentryConfig(nextConfig, {
silent: true,
applicationKey: 'nextjs-16-e2e',
applicationKeyExcludeDependencies: process.env.NEXT_PUBLIC_EXCLUDE_APPLICATION_KEY_DEPENDENCIES === '1',
release: process.env.E2E_RELEASE_NOT_INJECTED ? { name: 'foobar123', inject: false } : undefined,
reactComponentAnnotation: {
enabled: true,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
"@sentry/conventions": "0.33.0",
"@types/node": "^20",
"@types/pg": "^8.11.10",
"@types/react": "^19",
Expand Down Expand Up @@ -81,6 +82,11 @@
"label": "nextjs-16 (feedback, production)",
"assert-command": "NEXT_PUBLIC_E2E_FEEDBACK=1 pnpm test:prod tests/feedback.test.ts"
},
{
"build-command": "E2E_RELEASE_NOT_INJECTED=1 pnpm test:build",
"label": "nextjs-16 (turbopack, release not injected, production)",
"assert-command": "E2E_RELEASE_NOT_INJECTED=1 pnpm test:prod"
},
{
"build-command": "pnpm test:build-webpack",
"label": "nextjs-16 (webpack, production)",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { expect, test } from '@playwright/test';
import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
import { HTTP_SERVER, PAGELOAD } from '@sentry/conventions/op';

test.skip(!process.env.E2E_RELEASE_NOT_INJECTED, 'Only for builds with `release.inject: false`');

test('sends server and pageload spans with the release', async ({ page }) => {
const serverSpanPromise = waitForStreamedSpan('nextjs-16', span => {
return span.name === 'GET /pageload-tracing' && getSpanOp(span) === HTTP_SERVER && span.is_segment;
});
const pageloadSpanPromise = waitForStreamedSpan('nextjs-16', span => {
return span.name === '/pageload-tracing' && getSpanOp(span) === PAGELOAD && span.is_segment;
});

await page.goto('/pageload-tracing');

const [serverSpan, pageloadSpan] = await Promise.all([serverSpanPromise, pageloadSpanPromise]);
expect(serverSpan.attributes['sentry.release']?.value).toBe('foobar123');
expect(pageloadSpan.attributes['sentry.release']?.value).toBe('foobar123');
});

test('keeps the release out of the client bundles', async ({ page }) => {
const scriptBodies: Promise<string>[] = [];
page.on('response', response => {
if (response.url().includes('/_next/static/') && response.url().endsWith('.js')) {
scriptBodies.push(response.text());
}
});

const documentResponse = await page.goto('/pageload-tracing');
await page.waitForLoadState('networkidle');

expect(await documentResponse?.headerValue('server-timing')).toContain('sentry-release;desc="foobar123"');
expect(scriptBodies.length).toBeGreaterThan(0);
expect((await Promise.all(scriptBodies)).filter(body => body.includes('foobar123'))).toEqual([]);
});
3 changes: 2 additions & 1 deletion packages/nextjs/src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { isRedirectNavigationError } from '../common/nextNavigationErrorUtils';
import { getInjectedBasePath } from '../common/utils/basePath';
import { browserTracingIntegration } from './browserTracingIntegration';
import { nextjsClientStackFrameNormalizationIntegration } from './clientNormalizationIntegration';
import { getServerTimingRelease } from './release';
import { createNextRouteProvider } from './routing/routeProvider';
import { applyTunnelRouteOption } from './tunnelRoute';

Expand Down Expand Up @@ -56,7 +57,7 @@ export function init(userOptions: BrowserOptions): Client | undefined {
const opts = {
environment: options.environment || process.env.SENTRY_ENVIRONMENT || getClientVercelEnv() || process.env.NODE_ENV,
defaultIntegrations: getDefaultIntegrations(options),
release: process.env._sentryRelease || globalWithInjectedValues._sentryRelease,
release: process.env._sentryRelease || globalWithInjectedValues._sentryRelease || getServerTimingRelease(),
// Both route manifests are injected at build time, so route parameterization works from `init` on,
// including for the pageload span and with tracing disabled.
routeProvider: createNextRouteProvider(),
Expand Down
21 changes: 21 additions & 0 deletions packages/nextjs/src/client/release.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { WINDOW } from '@sentry/react';
import { RELEASE_SERVER_TIMING_NAME } from '../common/utils/releaseServerTiming';

/**
* Reads the release from the `Server-Timing` header of the document response, which `withSentryConfig` adds with
* `release.inject: false`.
*/
export function getServerTimingRelease(): string | undefined {
// The cast is required for the declaration build, which resolves `getEntriesByType('navigation')`
// to `PerformanceEntry[]` without `serverTiming`.
const navigation = WINDOW.performance?.getEntriesByType?.('navigation')[0] as PerformanceNavigationTiming | undefined;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
const description = navigation?.serverTiming?.find(entry => entry.name === RELEASE_SERVER_TIMING_NAME)?.description;
if (!description) {
return undefined;
}
try {
return decodeURIComponent(description);
} catch {
return undefined;
}
}
5 changes: 5 additions & 0 deletions packages/nextjs/src/common/utils/releaseServerTiming.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/**
* The name of the `Server-Timing` entry that carries the release to the browser SDK when the build keeps it out of
* the client bundles (`release.inject: false`).
*/
export const RELEASE_SERVER_TIMING_NAME = 'sentry-release';
32 changes: 28 additions & 4 deletions packages/nextjs/src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ type NextRewrite = {
destination: string;
};

type NextHeader = {
source: string;
headers: { key: string; value: string }[];
locale?: false;
};

export interface WebpackPluginInstance {
[index: string]: unknown;
apply: (compiler: unknown) => void;
Expand Down Expand Up @@ -48,6 +54,8 @@ export type NextConfigObject = {
fallback?: NextRewrite[];
}
>;
// Response headers to set on matching paths
headers?: () => Promise<NextHeader[]>;
cacheComponents?: boolean;
// Packages that Next.js compiles, also in `node_modules`
transpilePackages?: string[];
Expand Down Expand Up @@ -200,12 +208,28 @@ export type SentryBuildOptions = Omit<
/**
* Options related to managing the Sentry releases for a build.
*
* Note that `release.inject` is not configurable. The Next.js SDK always injects the release value
* itself, because the bundler plugin's own release injection breaks the `app` directory.
*
* More info: https://docs.sentry.io/product/releases/
*/
release?: Omit<NonNullable<BuildTimeOptionsBase['release']>, 'inject'>;
release?: Omit<NonNullable<BuildTimeOptionsBase['release']>, 'inject'> & {
/**
* Whether to inject the release into the client bundles.
*
* The release name usually changes on every commit, so the chunks that contain it get new content hashes, and
* new file names, on every release, and returning visitors download them again.
*
* Set this to `false` to keep the release out of the client bundles. The SDK then adds a `Server-Timing` header
* with the release to every page response, and the browser SDK reads it from there. This needs a page served
* over HTTPS (or from `localhost`) to a browser that exposes `Server-Timing` to scripts (Safari 16.4 or later),
* and a host that applies the `headers` of `next.config.js`. Events from other browsers have no release, unless
* you pass `release` to `Sentry.init`. With `output: 'export'` there is no server to send the header, so the SDK
* injects the release anyway.
*
* The server and edge SDKs get the release either way.
*
* @default true
*/
inject?: boolean;
};

/**
* Automatic instrumentation of server-side dependencies at build time.
Expand Down
6 changes: 6 additions & 0 deletions packages/nextjs/src/config/webpack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import type {
import { sentryOrchestrionWebpackPlugin } from '@sentry/server-utils/orchestrion/webpack';
import { DEFAULT_PAGE_EXTENSIONS, getNextjsVersion, getPackageModules } from './util';
import type { VercelCronsConfigResult } from './withSentryConfig/getFinalConfigObjectUtils';
import { shouldInjectReleaseIntoClient } from './withSentryConfig/release';
import { getTunnelRouteInjectedValues } from './withSentryConfig/tunnel';

// Next.js runs webpack 3 times, once for the client, the server, and for edge. Because we don't want to print certain
Expand Down Expand Up @@ -720,6 +721,8 @@ function addValueInjectionLoader({

const serverValues = {
...isomorphicValues,
// Without `release.inject`, `env` has no release, so the server SDK reads this one.
_sentryRelease: releaseName,
// Make sure that if we have a windows path, the backslashes are interpreted as such (rather than as escape
// characters)
_sentryRewriteFramesDistDir: userNextConfig.distDir?.replace(/\\/g, '\\\\') || '.next',
Expand All @@ -729,6 +732,9 @@ function addValueInjectionLoader({

const clientValues = {
...isomorphicValues,
SENTRY_RELEASE: shouldInjectReleaseIntoClient(userNextConfig, userSentryOptions)
? isomorphicValues.SENTRY_RELEASE
: undefined,
// Get the path part of `assetPrefix`, minus any trailing slash. (We use a placeholder for the origin if
// `assetPrefix` doesn't include one. Since we only care about the path, it doesn't matter what it is.)
_sentryRewriteFramesAssetPrefixPath: assetPrefix
Expand Down
4 changes: 3 additions & 1 deletion packages/nextjs/src/config/withSentryConfig/buildTime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as fs from 'fs';
import * as path from 'path';
import type { NextConfigObject, SentryBuildOptions } from '../types';
import { hasOnlyAppRouterPages } from './pagesRouterDetection';
import { shouldInjectReleaseIntoClient } from './release';
import { getTunnelRouteInjectedValues } from './tunnel';

/**
Expand Down Expand Up @@ -61,7 +62,8 @@ export function setUpBuildTimeVariables(
buildTimeVariables._experimentalThirdPartyOriginStackFrames = 'true';
}

if (releaseName) {
// `env` is inlined into the client bundles too. The server SDK also reads the injected global.
if (releaseName && shouldInjectReleaseIntoClient(userNextConfig, userSentryOptions)) {
buildTimeVariables._sentryRelease = releaseName;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
warnIfMissingInstrumentationFile,
warnIfMissingOnRouterTransitionStartHook,
} from './getFinalConfigObjectUtils';
import { maybeAddReleaseServerTimingHeader } from './release';

/**
* Materializes the final Next.js config object with Sentry's build-time integrations applied.
Expand All @@ -52,6 +53,7 @@ export function getFinalConfigObject(
const routeManifest = maybeCreateRouteManifest(incomingUserNextConfigObject, userSentryOptions);
const vercelCronsConfigResult = maybeGetVercelCronsConfig(userSentryOptions);
setUpBuildTimeVariables(incomingUserNextConfigObject, userSentryOptions, releaseName);
maybeAddReleaseServerTimingHeader(incomingUserNextConfigObject, userSentryOptions, releaseName);

const nextJsVersion = getNextjsVersion();
const nextMajor = getNextMajor(nextJsVersion);
Expand Down
39 changes: 39 additions & 0 deletions packages/nextjs/src/config/withSentryConfig/release.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { RELEASE_SERVER_TIMING_NAME } from '../../common/utils/releaseServerTiming';
import type { NextConfigObject, SentryBuildOptions } from '../types';

/**
* Whether the release goes into the client bundles. A static export has no server to send it in a header, so it
* always does.
*/
export function shouldInjectReleaseIntoClient(
userNextConfig: NextConfigObject,
userSentryOptions: SentryBuildOptions,
): boolean {
return userSentryOptions.release?.inject !== false || userNextConfig.output === 'export';
}

/**
* Adds the release in a `Server-Timing` header to every response outside of `/_next/`, for the browser SDK to read
* from the document response when the release is not in the client bundles.
*
* Note: this mutates `userNextConfig`.
*/
export function maybeAddReleaseServerTimingHeader(
userNextConfig: NextConfigObject,
userSentryOptions: SentryBuildOptions,
releaseName: string | undefined,
): void {
if (!releaseName || shouldInjectReleaseIntoClient(userNextConfig, userSentryOptions)) {
return;
}

// Encoded, so the value is valid in a header and has no `:` that Next.js would read as a path parameter.
const value = `${RELEASE_SERVER_TIMING_NAME};desc="${encodeURIComponent(releaseName)}"`;
const originalHeaders = userNextConfig.headers;
userNextConfig.headers = async () => [
// First, because Next.js lets the last matching header with the same key win, and the app's own
// `Server-Timing` header should not be replaced.
{ source: '/:path((?!_next/).*)', locale: false, headers: [{ key: 'Server-Timing', value }] },
...((await originalHeaders?.()) ?? []),
];
}
Loading
Loading