Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
42cb087
feat: Accept `tunnel: true` in `init` to enable the managed tunnel
logaretm Oct 8, 2026
2f9fbee
feat: Explain a managed tunnel that nothing on the server answers
logaretm Oct 15, 2026
b7759aa
fix(core): Keep the managed tunnel warning out of production bundles
logaretm Oct 16, 2026
de55542
fix(aws-serverless): Keep the managed tunnel when the Lambda extensio…
logaretm Oct 16, 2026
4466c2d
fix(core): Point Next.js users to `tunnelRoute` when the managed tunn…
logaretm Oct 16, 2026
ac8a68c
feat(browser): Send directly to Sentry when nothing answers the manag…
logaretm Oct 16, 2026
8d07f1e
fix(browser): Normalize the managed tunnel's base path like the serve…
logaretm Oct 19, 2026
afaaa0c
fix(browser): Keep the managed tunnel when Sentry answers 404 or 405 …
logaretm Oct 19, 2026
a387492
fix(browser): Send directly when anything but the tunnel answers a ma…
logaretm Oct 19, 2026
51664fc
ref(browser): Warn about a rejected DSN from the managed tunnel trans…
logaretm Oct 19, 2026
a61789b
ref(browser): Switch the managed tunnel to direct sends in one place
logaretm Oct 19, 2026
4ee4dd0
test(browser): Drop the server-side tunnel match from the browser tun…
logaretm Oct 19, 2026
a8699a4
ref(browser): Trim the managed tunnel comments
logaretm Oct 19, 2026
92f5265
fix(aws-serverless): Keep the Lambda extension for a relative tunnel …
logaretm Oct 19, 2026
c68139a
ref: Import the internal tunnel helpers under their `_INTERNAL_` names
logaretm Oct 22, 2026
02cfc41
ref: Narrow `tunnel` to the browser or server tunnel options per SDK
logaretm Oct 22, 2026
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
7 changes: 6 additions & 1 deletion packages/aws-serverless/src/init.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Integration, Options } from '@sentry/core';
import { applySdkMetadata, debug, envToBool, getSDKSource } from '@sentry/core';
import { _INTERNAL_resolveServerTunnelOption as resolveServerTunnelOption } from '@sentry/core/server';
import type { NodeClient, NodeOptions } from '@sentry/node';
import { getDefaultIntegrationsWithoutPerformance, initWithoutDefaultIntegrations } from '@sentry/node';
import { awsIntegration } from '@sentry/server-utils';
Expand Down Expand Up @@ -76,13 +77,17 @@ export function init(options: AwsServerlessOptions = {}): NodeClient | undefined
// 2. Environment variable SENTRY_LAYER_EXTENSION (if set)
// 3. Default logic based on sdkSource, tunnel, and proxy settings
const useLayerExtensionFromEnv = envToBool(process.env.SENTRY_LAYER_EXTENSION, { strict: true });
const defaultUseLayerExtension = sdkSource === 'aws-lambda-layer' && !options.tunnel && !proxyWouldInterfere;
// A relative path is the managed tunnel's path, not a transport URL.
const { tunnel, _managedTunnel } = resolveServerTunnelOption(options.tunnel);
const defaultUseLayerExtension = sdkSource === 'aws-lambda-layer' && !tunnel && !proxyWouldInterfere;
const useLayerExtension = options.useLayerExtension ?? useLayerExtensionFromEnv ?? defaultUseLayerExtension;

const opts = {
defaultIntegrations: getDefaultIntegrations(options),
useLayerExtension,
...options,
tunnel,
_managedTunnel,
};

if (opts.useLayerExtension) {
Expand Down
27 changes: 27 additions & 0 deletions packages/aws-serverless/test/init.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,33 @@ describe('init', () => {
);
});

test('keeps the managed tunnel when the Lambda extension takes over the transport', () => {
mockGetSDKSource.mockReturnValue('aws-lambda-layer');

init({ tunnel: true, useLayerExtension: true });

expect(mockInitWithoutDefaultIntegrations).toHaveBeenCalledWith(
expect.objectContaining({
tunnel: 'http://localhost:9000/envelope',
_managedTunnel: {},
}),
);
});

test('keeps the Lambda extension for a relative tunnel path, which is the managed tunnel to serve', () => {
mockGetSDKSource.mockReturnValue('aws-lambda-layer');

init({ tunnel: '/monitor' });

expect(mockInitWithoutDefaultIntegrations).toHaveBeenCalledWith(
expect.objectContaining({
useLayerExtension: true,
tunnel: 'http://localhost:9000/envelope',
_managedTunnel: { path: '/monitor' },
}),
);
});

test('should not set tunnel when Lambda extension is disabled', () => {
mockGetSDKSource.mockReturnValue('aws-lambda-layer');
const options: AwsServerlessOptions = {
Expand Down
10 changes: 9 additions & 1 deletion packages/browser/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import type {
BrowserTunnelOptions,
ClientOptions,
Event,
EventHint,
Options as CoreOptions,
ParameterizedString,
Scope,
SeverityLevel,
TunnelInit,
} from '@sentry/core';
import type { BrowserClientReplayOptions } from '@sentry/core/browser';
import type { RouteProvider } from '@sentry/browser-utils';
Expand Down Expand Up @@ -91,7 +93,13 @@ type BrowserSpecificOptions = BrowserClientReplayOptions &
* Configuration options for the Sentry Browser SDK.
* @see @sentry/core Options for more information.
*/
export type BrowserOptions = CoreOptions<BrowserTransportOptions> & BrowserSpecificOptions;
export type BrowserOptions = CoreOptions<BrowserTransportOptions> &
BrowserSpecificOptions & {
/**
* See {@link CoreOptions.tunnel}. The browser `init` also takes the browser-only {@link BrowserTunnelOptions}.
*/
tunnel?: TunnelInit<BrowserTunnelOptions>;
};

/**
* Configuration options for the Sentry Browser SDK Client class
Expand Down
9 changes: 8 additions & 1 deletion packages/browser/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { defaultStackParser } from './stack-parsers';
import { makeFetchTransport } from './transports/fetch';
import { normalizeStringifyValue } from './normalizeStringifyValue';
import { checkAndWarnIfIsEmbeddedBrowserExtension } from './utils/detectBrowserExtension';
import { makeManagedTunnelTransport, resolveBrowserTunnelOption } from './utils/managedTunnel';
Comment thread
logaretm marked this conversation as resolved.

/** Get the default integrations for the browser SDK. */
export function getDefaultIntegrations(_options: Options): Integration[] {
Expand Down Expand Up @@ -115,12 +116,18 @@ export function init(options: BrowserOptions = {}): Client | undefined {
defaultIntegrations,
});

const tunnelOptions = resolveBrowserTunnelOption(options);
const transport = options.transport || makeFetchTransport;

const clientOptions: BrowserClientOptions = {
...options,
...tunnelOptions,
enabled: shouldDisableBecauseIsBrowserExtenstion ? false : options.enabled,
stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),
integrations,
transport: options.transport || makeFetchTransport,
transport: tunnelOptions._managedTunnel
? makeManagedTunnelTransport(transport, options.transportOptions?.headers)
: transport,
Comment thread
logaretm marked this conversation as resolved.
};

setNormalizeStringifier(normalizeStringifyValue);
Expand Down
3 changes: 2 additions & 1 deletion packages/browser/src/transports/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/core';
import { createTransport, makePromiseBuffer } from '@sentry/core';
import { createTransport, makePromiseBuffer, TUNNEL_RESPONSE_HEADER } from '@sentry/core';
import { clearCachedImplementation, getNativeImplementation } from '@sentry/browser-utils';
import type { WINDOW } from '../helpers';
import type { BrowserTransportOptions } from './types';
Expand Down Expand Up @@ -50,6 +50,7 @@ export function makeFetchTransport(
headers: {
'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),
'retry-after': response.headers.get('Retry-After'),
'x-sentry-tunnel': response.headers.get(TUNNEL_RESPONSE_HEADER),
},
};
} catch (e) {
Expand Down
105 changes: 105 additions & 0 deletions packages/browser/src/utils/managedTunnel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import type { BrowserTunnelOptions, Envelope, Transport, TransportMakeRequestResponse } from '@sentry/core';
import {
debug,
getEnvelopeEndpointWithUrlEncodedAuth,
getTunnelPath,
makeDsn,
_INTERNAL_normalizeTunnelBasePath as normalizeTunnelBasePath,
} from '@sentry/core';
import { DEBUG_BUILD } from '../debug-build';
import type { BrowserOptions } from '../client';
import type { BrowserTransportOptions } from '../transports/types';

/**
* Resolves `tunnel: true` or {@link BrowserTunnelOptions} to the same-origin path the server derives from the DSN.
*/
export function resolveBrowserTunnelOption(
options: BrowserOptions,
): Pick<BrowserOptions, 'transportOptions' | '_managedTunnel'> & { tunnel: string | undefined } {
const { tunnel, dsn, transportOptions } = options;
if (typeof tunnel === 'string' || !tunnel) {
return { tunnel, transportOptions };
}

const tunnelOptions: BrowserTunnelOptions = tunnel === true ? {} : tunnel;
const tunnelPath = tunnelOptions.path ?? (dsn && getTunnelPath(dsn));
if (!tunnelPath) {
return { tunnel: undefined, transportOptions };
}

const basePath = normalizeTunnelBasePath(tunnelOptions.basePath);
const resolvedTunnel = `${basePath}${tunnelPath}${tunnelOptions.trailingSlash ? '/' : ''}`;

DEBUG_BUILD && debug.log(`Tunneling events to "${resolvedTunnel}"`);

return {
tunnel: resolvedTunnel,
_managedTunnel: tunnelOptions,
// CSRF protection (SvelteKit, Astro) rejects the default `text/plain` POST as a form submission.
transportOptions: {
...transportOptions,
headers: { 'Content-Type': 'application/x-sentry-envelope', ...transportOptions?.headers },
},
};
}
Comment thread
logaretm marked this conversation as resolved.

let hasWarnedAboutRejectedDsn = false;

/**
* Falls back to sending directly when nothing on this origin serves the managed tunnel. An envelope is resent only
* when the response proves it never reached Sentry.
*/
export function makeManagedTunnelTransport(
makeTransport: (options: BrowserTransportOptions) => Transport,
directHeaders: BrowserTransportOptions['headers'],
): (options: BrowserTransportOptions) => Transport {
return options => {
const tunnelTransport = makeTransport(options);
let directTransport: Transport | undefined;

return {
async send(envelope: Envelope): Promise<TransportMakeRequestResponse> {
if (directTransport) {
return directTransport.send(envelope);
}

const response = await tunnelTransport.send(envelope);
const statusCode = response.statusCode || 0;

if (response.headers?.['x-sentry-tunnel']) {
if (DEBUG_BUILD && statusCode === 403 && !hasWarnedAboutRejectedDsn) {
hasWarnedAboutRejectedDsn = true;
debug.warn(
`The managed tunnel at "${options.url}" rejected this DSN, so events sent through it are lost. Add it to the server's \`allowedDsns\`.`,
);
}
Comment thread
logaretm marked this conversation as resolved.

return response;
}

// Not the tunnel: a 4xx never reached Sentry so it's resent, a 2xx may have, so only later envelopes go direct.
const rejected = statusCode >= 400 && statusCode < 500;
const { dsn, sdk } = envelope[0];
const components = (rejected || (statusCode >= 200 && statusCode < 300)) && dsn && makeDsn(dsn);
if (!components) {
return response;
}

DEBUG_BUILD &&
debug.warn(`Sending to Sentry directly: "${options.url}" answered ${statusCode} instead of the tunnel.`);
directTransport ??= makeTransport({
...options,
url: getEnvelopeEndpointWithUrlEncodedAuth(components, undefined, sdk),
headers: directHeaders,
});

return rejected ? directTransport.send(envelope) : response;
},
async flush(timeout?: number): Promise<boolean> {
const results = await Promise.all([tunnelTransport.flush(timeout), directTransport?.flush(timeout) ?? true]);

return results.every(Boolean);
},
};
};
}
3 changes: 2 additions & 1 deletion packages/browser/test/transports/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,10 @@ describe('fetchTransport', () => {
expect(headers.get).toHaveBeenCalledTimes(0);
await transport.send(ERROR_ENVELOPE);

expect(headers.get).toHaveBeenCalledTimes(2);
expect(headers.get).toHaveBeenCalledTimes(3);
expect(headers.get).toHaveBeenCalledWith('X-Sentry-Rate-Limits');
expect(headers.get).toHaveBeenCalledWith('Retry-After');
expect(headers.get).toHaveBeenCalledWith('X-Sentry-Tunnel');
});

it('allows for custom options to be passed in', async () => {
Expand Down
Loading
Loading