Skip to content

Commit 43a0ec7

Browse files
committed
only run beforeNavigate if provided by user
1 parent e3bab53 commit 43a0ec7

File tree

5 files changed

+36
-31
lines changed

5 files changed

+36
-31
lines changed

packages/tracing/src/browser/browsertracing.ts

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313
registerRequestInstrumentation,
1414
RequestInstrumentationOptions,
1515
} from './request';
16-
import { defaultBeforeNavigate, defaultRoutingInstrumentation } from './router';
16+
import { defaultRoutingInstrumentation } from './router';
1717

1818
export const DEFAULT_MAX_TRANSACTION_DURATION_SECONDS = 600;
1919

@@ -61,12 +61,17 @@ export interface BrowserTracingOptions extends RequestInstrumentationOptions {
6161
markBackgroundTransactions: boolean;
6262

6363
/**
64-
* beforeNavigate is called before a pageload/navigation transaction is created and allows for users
65-
* to set custom transaction context. Default behavior is to return `window.location.pathname`.
64+
* beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction
65+
* context data, or drop the transaction entirely (by setting `sampled = false` in the context).
6666
*
67-
* If undefined is returned, a pageload/navigation transaction will not be created.
67+
* Note: For legacy reasons, transactions can also be dropped by returning `undefined`, though that option may
68+
* disappear in the future.
69+
*
70+
* @param context: The context data which will be passed to `startTransaction` by default
71+
*
72+
* @returns A (potentially) modified context object, with `sampled = false` if the transaction should be dropped.
6873
*/
69-
beforeNavigate(context: TransactionContext): TransactionContext | undefined;
74+
beforeNavigate?(context: TransactionContext): TransactionContext | undefined;
7075

7176
/**
7277
* Instrumentation that creates routing change transactions. By default creates
@@ -80,7 +85,6 @@ export interface BrowserTracingOptions extends RequestInstrumentationOptions {
8085
}
8186

8287
const DEFAULT_BROWSER_TRACING_OPTIONS = {
83-
beforeNavigate: defaultBeforeNavigate,
8488
idleTimeout: DEFAULT_IDLE_TIMEOUT,
8589
markBackgroundTransactions: true,
8690
maxTransactionDuration: DEFAULT_MAX_TRANSACTION_DURATION_SECONDS,
@@ -188,21 +192,25 @@ export class BrowserTracing implements Integration {
188192
// eslint-disable-next-line @typescript-eslint/unbound-method
189193
const { beforeNavigate, idleTimeout, maxTransactionDuration } = this.options;
190194

191-
// if beforeNavigate returns undefined, we should not start a transaction.
192-
const ctx = beforeNavigate({
195+
const expandedContext = {
193196
...context,
194197
...getHeaderContext(),
195198
trimEnd: true,
196-
});
199+
};
200+
const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;
197201

198-
if (ctx === undefined) {
199-
logger.log(`[Tracing] Did not create ${context.op} idleTransaction due to beforeNavigate`);
200-
return undefined;
202+
// TODO (kmclb): for backwards compatibility reasons, beforeNavigate can return undefined to "drop" the transaction
203+
// (prevent it from being sent to Sentry). This can be removed in V6, after which time modifiedContext and
204+
// finalContext will be one and the same.
205+
const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;
206+
207+
if (finalContext.sampled === false) {
208+
logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);
201209
}
202210

203211
const hub = this._getCurrentHub();
204-
logger.log(`[Tracing] starting ${ctx.op} idleTransaction on scope`);
205-
const idleTransaction = startIdleTransaction(hub, ctx, idleTimeout, true);
212+
logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);
213+
const idleTransaction = startIdleTransaction(hub, finalContext, idleTimeout, true);
206214
idleTransaction.registerBeforeFinishCallback((transaction, endTimestamp) => {
207215
this._metrics.addPerformanceEntries(transaction);
208216
adjustTransactionDuration(secToMs(maxTransactionDuration), transaction, endTimestamp);

packages/tracing/src/browser/router.ts

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,3 @@ export function defaultRoutingInstrumentation<T extends TransactionType>(
5454
});
5555
}
5656
}
57-
58-
/** default implementation of Browser Tracing before navigate */
59-
export function defaultBeforeNavigate(context: TransactionContext): TransactionContext | undefined {
60-
return context;
61-
}

packages/tracing/test/browser/browsertracing.test.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,6 @@ describe('BrowserTracing', () => {
7676
const browserTracing = createBrowserTracing();
7777

7878
expect(browserTracing.options).toEqual({
79-
beforeNavigate: expect.any(Function),
8079
idleTimeout: DEFAULT_IDLE_TIMEOUT,
8180
markBackgroundTransactions: true,
8281
maxTransactionDuration: DEFAULT_MAX_TRANSACTION_DURATION_SECONDS,
@@ -177,14 +176,14 @@ describe('BrowserTracing', () => {
177176
expect(mockBeforeNavigation).toHaveBeenCalledTimes(1);
178177
});
179178

180-
it('does not create a transaction if it returns undefined', () => {
179+
it('creates an unsampled transaction if it returns undefined', () => {
181180
const mockBeforeNavigation = jest.fn().mockReturnValue(undefined);
182181
createBrowserTracing(true, {
183182
beforeNavigate: mockBeforeNavigation,
184183
routingInstrumentation: customRoutingInstrumentation,
185184
});
186185
const transaction = getActiveTransaction(hub) as IdleTransaction;
187-
expect(transaction).not.toBeDefined();
186+
expect(transaction.sampled).toBe(false);
188187

189188
expect(mockBeforeNavigation).toHaveBeenCalledTimes(1);
190189
});

packages/tracing/test/browser/router.test.ts

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { JSDOM } from 'jsdom';
22

3-
import { defaultBeforeNavigate, defaultRoutingInstrumentation } from '../../src/browser/router';
3+
import { defaultRoutingInstrumentation } from '../../src/browser/router';
44

55
let mockChangeHistory: ({ to, from }: { to: string; from?: string }) => void = () => undefined;
66
let addInstrumentationHandlerType: string = '';
@@ -15,13 +15,6 @@ jest.mock('@sentry/utils', () => {
1515
};
1616
});
1717

18-
describe('defaultBeforeNavigate()', () => {
19-
it('returns a context', () => {
20-
const ctx = { name: 'testing', status: 'ok' };
21-
expect(defaultBeforeNavigate(ctx)).toBe(ctx);
22-
});
23-
});
24-
2518
describe('defaultRoutingInstrumentation', () => {
2619
const mockFinish = jest.fn();
2720
const startTransaction = jest.fn().mockReturnValue({ finish: mockFinish });

packages/tracing/test/hub.test.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ describe('Hub', () => {
2222
});
2323

2424
describe('getTransaction()', () => {
25-
it('should find a transaction which has been set on the scope', () => {
25+
it('should find a sampled transaction which has been set on the scope', () => {
2626
const hub = new Hub(new BrowserClient({ tracesSampleRate: 1 }));
2727
const transaction = hub.startTransaction({ name: 'dogpark' });
2828
hub.configureScope(scope => {
@@ -32,6 +32,16 @@ describe('Hub', () => {
3232
expect(hub.getScope()?.getTransaction()).toBe(transaction);
3333
});
3434

35+
it('should find an unsampled transaction which has been set on the scope', () => {
36+
const hub = new Hub(new BrowserClient({ tracesSampleRate: 1 }));
37+
const transaction = hub.startTransaction({ name: 'dogpark', sampled: false });
38+
hub.configureScope(scope => {
39+
scope.setSpan(transaction);
40+
});
41+
42+
expect(hub.getScope()?.getTransaction()).toBe(transaction);
43+
});
44+
3545
it("should not find an open transaction if it's not on the scope", () => {
3646
const hub = new Hub(new BrowserClient({ tracesSampleRate: 1 }));
3747
hub.startTransaction({ name: 'dogpark' });

0 commit comments

Comments
 (0)