-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathinstrumentation.tsx
More file actions
1388 lines (1216 loc) · 48.9 KB
/
instrumentation.tsx
File metadata and controls
1388 lines (1216 loc) · 48.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable max-lines */
// Inspired from Donnie McNeal's solution:
// https://gist.github.com/wontondon/e8c4bdf2888875e4c755712e99279536
import {
browserTracingIntegration,
startBrowserTracingNavigationSpan,
startBrowserTracingPageLoadSpan,
WINDOW,
} from '@sentry/browser';
import type { Client, Integration, Span } from '@sentry/core';
import {
addNonEnumerableProperty,
debug,
getClient,
getCurrentScope,
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
spanToJSON,
} from '@sentry/core';
import * as React from 'react';
import { DEBUG_BUILD } from '../debug-build';
import { hoistNonReactStatics } from '../hoist-non-react-statics';
import type {
Action,
AgnosticDataRouteMatch,
CreateRouterFunction,
CreateRoutesFromChildren,
Location,
MatchRoutes,
RouteMatch,
RouteObject,
Router,
RouterState,
UseEffect,
UseLocation,
UseNavigationType,
UseRoutes,
} from '../types';
import { checkRouteForAsyncHandler } from './lazy-routes';
import {
clearNavigationContext,
getActiveRootSpan,
initializeRouterUtils,
resolveRouteNameAndSource,
setNavigationContext,
transactionNameHasWildcard,
} from './utils';
let _useEffect: UseEffect;
let _useLocation: UseLocation;
let _useNavigationType: UseNavigationType;
let _createRoutesFromChildren: CreateRoutesFromChildren;
let _matchRoutes: MatchRoutes;
let _enableAsyncRouteHandlers: boolean = false;
let _lazyRouteTimeout = 3000;
let _lazyRouteManifest: string[] | undefined;
let _basename: string = '';
const CLIENTS_WITH_INSTRUMENT_NAVIGATION = new WeakSet<Client>();
// Prevents duplicate spans when router.subscribe fires multiple times
const activeNavigationSpans = new WeakMap<
Client,
{ span: Span; routeName: string; pathname: string; locationKey: string; isPlaceholder?: boolean }
>();
// Exported for testing only
export const allRoutes = new Set<RouteObject>();
// Tracks lazy route loads to wait before finalizing span names
const pendingLazyRouteLoads = new WeakMap<Span, Set<Promise<unknown>>>();
// Tracks deferred lazy route promises that can be resolved when patchRoutesOnNavigation is called
const deferredLazyRouteResolvers = new WeakMap<Span, () => void>();
/**
* Schedules a callback using requestAnimationFrame when available (browser),
* or falls back to setTimeout for SSR environments (Node.js, createMemoryRouter tests).
*/
function scheduleCallback(callback: () => void): number {
if (WINDOW?.requestAnimationFrame) {
return WINDOW.requestAnimationFrame(callback);
}
return setTimeout(callback, 0) as unknown as number;
}
/**
* Cancels a scheduled callback, handling both RAF (browser) and timeout (SSR) IDs.
*/
function cancelScheduledCallback(id: number): void {
if (WINDOW?.cancelAnimationFrame) {
WINDOW.cancelAnimationFrame(id);
} else {
clearTimeout(id);
}
}
/**
* Computes location key for duplicate detection. Normalizes undefined/null to empty strings.
* Exported for testing.
*/
export function computeLocationKey(location: Location): string {
return `${location.pathname}${location.search || ''}${location.hash || ''}`;
}
/**
* Checks if a route name is parameterized (contains route parameters like :id or wildcards like *)
* vs a raw URL path.
*/
function isParameterizedRoute(routeName: string): boolean {
return routeName.includes(':') || routeName.includes('*');
}
/**
* Determines if a navigation should be skipped as a duplicate, and if an existing span should be updated.
* Exported for testing.
*
* @returns An object with:
* - skip: boolean - Whether to skip creating a new span
* - shouldUpdate: boolean - Whether to update the existing span name (wildcard upgrade)
*/
export function shouldSkipNavigation(
trackedNav:
| { span: Span; routeName: string; pathname: string; locationKey: string; isPlaceholder?: boolean }
| undefined,
locationKey: string,
proposedName: string,
spanHasEnded: boolean,
): { skip: boolean; shouldUpdate: boolean } {
if (!trackedNav) {
return { skip: false, shouldUpdate: false };
}
// Check if this is a duplicate navigation (same location)
// 1. If it's a placeholder, it's always a duplicate (we're waiting for the real one)
// 2. If it's a real span, it's a duplicate only if it hasn't ended yet
const isDuplicate = trackedNav.locationKey === locationKey && (trackedNav.isPlaceholder || !spanHasEnded);
if (isDuplicate) {
// Check if we should update the span name with a better route
// Allow updates if:
// 1. Current has wildcard and new doesn't (wildcard → parameterized upgrade)
// 2. Current is raw path and new is parameterized (raw → parameterized upgrade)
// 3. New name is different and more specific (longer, indicating nested routes resolved)
const currentHasWildcard = !!trackedNav.routeName && transactionNameHasWildcard(trackedNav.routeName);
const proposedHasWildcard = transactionNameHasWildcard(proposedName);
const currentIsParameterized = !!trackedNav.routeName && isParameterizedRoute(trackedNav.routeName);
const proposedIsParameterized = isParameterizedRoute(proposedName);
const isWildcardUpgrade = currentHasWildcard && !proposedHasWildcard;
const isRawToParameterized = !currentIsParameterized && proposedIsParameterized;
const isMoreSpecific =
proposedName !== trackedNav.routeName &&
proposedName.length > (trackedNav.routeName?.length || 0) &&
!proposedHasWildcard;
const shouldUpdate = !!(trackedNav.routeName && (isWildcardUpgrade || isRawToParameterized || isMoreSpecific));
return { skip: true, shouldUpdate };
}
return { skip: false, shouldUpdate: false };
}
export interface ReactRouterOptions {
useEffect: UseEffect;
useLocation: UseLocation;
useNavigationType: UseNavigationType;
createRoutesFromChildren: CreateRoutesFromChildren;
matchRoutes: MatchRoutes;
/**
* Whether to strip the basename from the pathname when creating transactions.
*
* This is useful for applications that use a basename in their routing setup.
* @default false
*/
stripBasename?: boolean;
/**
* Enables support for async route handlers.
*
* This allows Sentry to track and instrument routes dynamically resolved from async handlers.
* @default false
*/
enableAsyncRouteHandlers?: boolean;
/**
* Maximum time (in milliseconds) to wait for lazy routes to load before finalizing span names.
*
* - Set to `0` to not wait at all (immediate finalization)
* - Set to `Infinity` to wait as long as possible (capped at `finalTimeout` to prevent indefinite hangs)
* - Negative values will fall back to the default
*
* Defaults to 3× the configured `idleTimeout` (default: 3000ms).
*
* @default idleTimeout * 3
*/
lazyRouteTimeout?: number;
/**
* Static route manifest for resolving parameterized route names with lazy routes.
*
* Requires `enableAsyncRouteHandlers: true`. When provided, the manifest is used
* as the primary source for determining transaction names. This is more reliable
* than depending on React Router's lazy route resolution timing.
*
* @example
* ```ts
* lazyRouteManifest: [
* '/',
* '/users',
* '/users/:userId',
* '/org/:orgSlug/projects/:projectId',
* ]
* ```
*/
lazyRouteManifest?: string[];
}
type V6CompatibleVersion = '6' | '7';
export function addResolvedRoutesToParent(resolvedRoutes: RouteObject[], parentRoute: RouteObject): void {
const existingChildren = parentRoute.children || [];
const newRoutes = resolvedRoutes.filter(
newRoute =>
!existingChildren.some(
existing =>
existing === newRoute ||
(newRoute.path && existing.path === newRoute.path) ||
(newRoute.id && existing.id === newRoute.id),
),
);
if (newRoutes.length > 0) {
parentRoute.children = [...existingChildren, ...newRoutes];
}
}
/** Registers a pending lazy route load promise for a span. */
function trackLazyRouteLoad(span: Span, promise: Promise<unknown>): void {
let promises = pendingLazyRouteLoads.get(span);
if (!promises) {
promises = new Set();
pendingLazyRouteLoads.set(span, promises);
}
promises.add(promise);
// Clean up when promise resolves/rejects
promise.finally(() => {
const currentPromises = pendingLazyRouteLoads.get(span);
if (currentPromises) {
currentPromises.delete(promise);
}
});
}
/**
* Creates a deferred promise for a span that will be resolved when patchRoutesOnNavigation is called.
* This ensures that patchedEnd waits for patchRoutesOnNavigation to be called before ending the span.
*/
function createDeferredLazyRoutePromise(span: Span): void {
const deferredPromise = new Promise<void>(resolve => {
deferredLazyRouteResolvers.set(span, resolve);
});
trackLazyRouteLoad(span, deferredPromise);
}
/**
* Resolves the deferred lazy route promise for a span.
* Called when patchRoutesOnNavigation is invoked.
*/
function resolveDeferredLazyRoutePromise(span: Span): void {
const resolver = deferredLazyRouteResolvers.get(span);
if (resolver) {
resolver();
deferredLazyRouteResolvers.delete(span);
// Clear the flag so patchSpanEnd doesn't wait unnecessarily for routes that have already loaded
if ((span as unknown as Record<string, boolean>).__sentry_may_have_lazy_routes__) {
(span as unknown as Record<string, boolean>).__sentry_may_have_lazy_routes__ = false;
}
}
}
/**
* Processes resolved routes by adding them to allRoutes and checking for nested async handlers.
* When capturedSpan is provided, updates that specific span instead of the current active span.
* This prevents race conditions where a lazy handler resolves after the user has navigated away.
*/
export function processResolvedRoutes(
resolvedRoutes: RouteObject[],
parentRoute?: RouteObject,
currentLocation: Location | null = null,
capturedSpan?: Span,
): void {
resolvedRoutes.forEach(child => {
allRoutes.add(child);
// Only check for async handlers if the feature is enabled
if (_enableAsyncRouteHandlers) {
checkRouteForAsyncHandler(child, processResolvedRoutes);
}
});
if (parentRoute) {
// If a parent route is provided, add the resolved routes as children to the parent route
addResolvedRoutesToParent(resolvedRoutes, parentRoute);
}
// Use captured span if provided, otherwise fall back to current active span
const targetSpan = capturedSpan ?? getActiveRootSpan();
if (targetSpan) {
const spanJson = spanToJSON(targetSpan);
// Skip update if span has already ended (timestamp is set when span.end() is called)
if (spanJson.timestamp) {
DEBUG_BUILD && debug.warn('[React Router] Lazy handler resolved after span ended - skipping update');
return;
}
const spanOp = spanJson.op;
// Use captured location for route matching (ensures we match against the correct route)
// Fall back to window.location only if no captured location and no captured span
// (i.e., this is not from an async handler)
let location = currentLocation;
if (!location && !capturedSpan) {
if (typeof WINDOW !== 'undefined') {
const globalLocation = WINDOW.location;
if (globalLocation?.pathname) {
location = { pathname: globalLocation.pathname };
}
}
}
if (location) {
if (spanOp === 'pageload') {
// Re-run the pageload transaction update with the newly loaded routes
updatePageloadTransaction({
activeRootSpan: targetSpan,
location: { pathname: location.pathname },
routes: Array.from(allRoutes),
allRoutes: Array.from(allRoutes),
});
} else if (spanOp === 'navigation') {
// For navigation spans, update the name with the newly loaded routes
updateNavigationSpan(targetSpan, location, Array.from(allRoutes), false, _matchRoutes);
}
}
}
}
/**
* Updates a navigation span with the correct route name after lazy routes have been loaded.
*/
export function updateNavigationSpan(
activeRootSpan: Span,
location: Location,
allRoutes: RouteObject[],
forceUpdate = false,
matchRoutes: MatchRoutes,
): void {
const spanJson = spanToJSON(activeRootSpan);
const currentName = spanJson.description;
const hasBeenNamed = (activeRootSpan as { __sentry_navigation_name_set__?: boolean })?.__sentry_navigation_name_set__;
const currentNameHasWildcard = currentName && transactionNameHasWildcard(currentName);
const shouldUpdate = !hasBeenNamed || forceUpdate || currentNameHasWildcard;
if (shouldUpdate && !spanJson.timestamp) {
const currentBranches = matchRoutes(allRoutes, location);
const [name, source] = resolveRouteNameAndSource(
location,
allRoutes,
allRoutes,
(currentBranches as RouteMatch[]) || [],
_basename,
_lazyRouteManifest,
_enableAsyncRouteHandlers,
);
const currentSource = spanJson.data?.[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
const isImprovement =
name &&
(!currentName || // No current name - always set
(!hasBeenNamed && (currentSource !== 'route' || source === 'route')) || // Not finalized - allow unless downgrading route→url
(currentSource !== 'route' && source === 'route') || // URL → route upgrade
(currentSource === 'route' && source === 'route' && currentNameHasWildcard)); // Route → better route (only if current has wildcard)
if (isImprovement) {
activeRootSpan.updateName(name);
activeRootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source);
// Only mark as finalized for non-wildcard route names (allows URL→route upgrades).
if (!transactionNameHasWildcard(name) && source === 'route') {
addNonEnumerableProperty(
activeRootSpan as { __sentry_navigation_name_set__?: boolean },
'__sentry_navigation_name_set__',
true,
);
}
}
}
}
function setupRouterSubscription(
router: Router,
routes: RouteObject[],
version: V6CompatibleVersion,
basename: string | undefined,
activeRootSpan: Span | undefined,
): void {
let isInitialPageloadComplete = false;
let hasSeenPageloadSpan = !!activeRootSpan && spanToJSON(activeRootSpan).op === 'pageload';
let hasSeenPopAfterPageload = false;
let scheduledNavigationHandler: number | null = null;
let lastHandledPathname: string | null = null;
router.subscribe((state: RouterState) => {
if (!isInitialPageloadComplete) {
const currentRootSpan = getActiveRootSpan();
const isCurrentlyInPageload = currentRootSpan && spanToJSON(currentRootSpan).op === 'pageload';
if (isCurrentlyInPageload) {
hasSeenPageloadSpan = true;
} else if (hasSeenPageloadSpan) {
if (state.historyAction === 'POP' && !hasSeenPopAfterPageload) {
hasSeenPopAfterPageload = true;
} else {
isInitialPageloadComplete = true;
}
}
}
const shouldHandleNavigation =
state.historyAction === 'PUSH' || (state.historyAction === 'POP' && isInitialPageloadComplete);
if (shouldHandleNavigation) {
// Include search and hash to allow query/hash-only navigations
// Use computeLocationKey() to ensure undefined/null values are normalized to empty strings
const currentLocationKey = computeLocationKey(state.location);
const navigationHandler = (): void => {
// Prevent multiple calls for the same location within the same navigation cycle
if (lastHandledPathname === currentLocationKey) {
return;
}
lastHandledPathname = currentLocationKey;
scheduledNavigationHandler = null;
handleNavigation({
location: state.location,
routes,
navigationType: state.historyAction,
version,
basename,
allRoutes: Array.from(allRoutes),
});
};
if (state.navigation.state !== 'idle') {
// Navigation in progress - reset if location changed
if (lastHandledPathname !== currentLocationKey) {
lastHandledPathname = null;
}
// Cancel any previously scheduled handler to avoid duplicates
if (scheduledNavigationHandler !== null) {
cancelScheduledCallback(scheduledNavigationHandler);
}
scheduledNavigationHandler = scheduleCallback(navigationHandler);
} else {
// Navigation completed - cancel scheduled handler if any, then call immediately
if (scheduledNavigationHandler !== null) {
cancelScheduledCallback(scheduledNavigationHandler);
scheduledNavigationHandler = null;
}
navigationHandler();
// Don't reset - next navigation cycle resets to prevent duplicates within same cycle.
}
}
});
}
/**
* Creates a wrapCreateBrowserRouter function that can be used with all React Router v6 compatible versions.
*/
export function createV6CompatibleWrapCreateBrowserRouter<
TState extends RouterState = RouterState,
TRouter extends Router<TState> = Router<TState>,
>(
createRouterFunction: CreateRouterFunction<TState, TRouter>,
version: V6CompatibleVersion,
): CreateRouterFunction<TState, TRouter> {
if (!_useEffect || !_useLocation || !_useNavigationType || !_matchRoutes) {
DEBUG_BUILD &&
debug.warn(
`reactRouterV${version}Instrumentation was unable to wrap the \`createRouter\` function because of one or more missing parameters.`,
);
return createRouterFunction;
}
return function (routes: RouteObject[], opts?: Record<string, unknown> & { basename?: string }): TRouter {
addRoutesToAllRoutes(routes);
if (_enableAsyncRouteHandlers) {
for (const route of routes) {
checkRouteForAsyncHandler(route, processResolvedRoutes);
}
}
// Capture the active span BEFORE creating the router.
// This is important because the span might end (due to idle timeout) before
// patchRoutesOnNavigation is called by React Router.
const activeRootSpan = getActiveRootSpan();
// If patchRoutesOnNavigation is provided and we have an active span,
// mark the span as having potential lazy routes and create a deferred promise.
const hasPatchRoutesOnNavigation =
opts && 'patchRoutesOnNavigation' in opts && typeof opts.patchRoutesOnNavigation === 'function';
if (hasPatchRoutesOnNavigation && activeRootSpan) {
// Mark the span as potentially having lazy routes
addNonEnumerableProperty(
activeRootSpan as unknown as Record<string, boolean>,
'__sentry_may_have_lazy_routes__',
true,
);
createDeferredLazyRoutePromise(activeRootSpan);
}
// Pass the captured span to wrapPatchRoutesOnNavigation so it uses the same span
// even if the span has ended by the time patchRoutesOnNavigation is called.
const wrappedOpts = wrapPatchRoutesOnNavigation(opts, false, activeRootSpan);
const router = createRouterFunction(routes, wrappedOpts);
const basename = opts?.basename;
if (router.state.historyAction === 'POP' && activeRootSpan) {
updatePageloadTransaction({
activeRootSpan,
location: router.state.location,
routes,
basename,
allRoutes: Array.from(allRoutes),
});
}
// Store basename for use in updateNavigationSpan
_basename = basename || '';
setupRouterSubscription(router, routes, version, basename, activeRootSpan);
return router;
};
}
/**
* Creates a wrapCreateMemoryRouter function that can be used with all React Router v6 compatible versions.
*/
export function createV6CompatibleWrapCreateMemoryRouter<
TState extends RouterState = RouterState,
TRouter extends Router<TState> = Router<TState>,
>(
createRouterFunction: CreateRouterFunction<TState, TRouter>,
version: V6CompatibleVersion,
): CreateRouterFunction<TState, TRouter> {
if (!_useEffect || !_useLocation || !_useNavigationType || !_matchRoutes) {
DEBUG_BUILD &&
debug.warn(
`reactRouterV${version}Instrumentation was unable to wrap the \`createMemoryRouter\` function because of one or more missing parameters.`,
);
return createRouterFunction;
}
return function (
routes: RouteObject[],
opts?: Record<string, unknown> & {
basename?: string;
initialEntries?: (string | { pathname: string })[];
initialIndex?: number;
},
): TRouter {
addRoutesToAllRoutes(routes);
if (_enableAsyncRouteHandlers) {
for (const route of routes) {
checkRouteForAsyncHandler(route, processResolvedRoutes);
}
}
// Capture the active span BEFORE creating the router (same as browser router)
const memoryActiveRootSpanEarly = getActiveRootSpan();
// If patchRoutesOnNavigation is provided and we have an active span,
// mark the span as having potential lazy routes and create a deferred promise.
const hasPatchRoutesOnNavigation =
opts && 'patchRoutesOnNavigation' in opts && typeof opts.patchRoutesOnNavigation === 'function';
if (hasPatchRoutesOnNavigation && memoryActiveRootSpanEarly) {
addNonEnumerableProperty(
memoryActiveRootSpanEarly as unknown as Record<string, boolean>,
'__sentry_may_have_lazy_routes__',
true,
);
createDeferredLazyRoutePromise(memoryActiveRootSpanEarly);
}
const wrappedOpts = wrapPatchRoutesOnNavigation(opts, true, memoryActiveRootSpanEarly);
const router = createRouterFunction(routes, wrappedOpts);
const basename = opts?.basename;
let initialEntry = undefined;
const initialEntries = opts?.initialEntries;
const initialIndex = opts?.initialIndex;
const hasOnlyOneInitialEntry = initialEntries && initialEntries.length === 1;
const hasIndexedEntry = initialIndex !== undefined && initialEntries && initialEntries[initialIndex];
initialEntry = hasOnlyOneInitialEntry
? initialEntries[0]
: hasIndexedEntry
? initialEntries[initialIndex]
: undefined;
const location = initialEntry
? typeof initialEntry === 'string'
? { pathname: initialEntry }
: initialEntry
: router.state.location;
const memoryActiveRootSpan = getActiveRootSpan();
if (router.state.historyAction === 'POP' && memoryActiveRootSpan) {
updatePageloadTransaction({
activeRootSpan: memoryActiveRootSpan,
location,
routes,
basename,
allRoutes: Array.from(allRoutes),
});
}
// Store basename for use in updateNavigationSpan
_basename = basename || '';
setupRouterSubscription(router, routes, version, basename, memoryActiveRootSpan);
return router;
};
}
/**
* Creates a browser tracing integration that can be used with all React Router v6 compatible versions.
*/
export function createReactRouterV6CompatibleTracingIntegration(
options: Parameters<typeof browserTracingIntegration>[0] & ReactRouterOptions,
version: V6CompatibleVersion,
): Integration {
const integration = browserTracingIntegration({ ...options, instrumentPageLoad: false, instrumentNavigation: false });
const {
useEffect,
useLocation,
useNavigationType,
createRoutesFromChildren,
matchRoutes,
stripBasename,
enableAsyncRouteHandlers = false,
instrumentPageLoad = true,
instrumentNavigation = true,
lazyRouteTimeout,
lazyRouteManifest,
} = options;
return {
...integration,
setup(client) {
integration.setup(client);
const finalTimeout = options.finalTimeout ?? 30000;
const defaultMaxWait = (options.idleTimeout ?? 1000) * 3;
const configuredMaxWait = lazyRouteTimeout ?? defaultMaxWait;
// Cap Infinity at finalTimeout to prevent indefinite hangs
if (configuredMaxWait === Infinity) {
_lazyRouteTimeout = finalTimeout;
DEBUG_BUILD &&
debug.log(
'[React Router] lazyRouteTimeout set to Infinity, capping at finalTimeout:',
finalTimeout,
'ms to prevent indefinite hangs',
);
} else if (Number.isNaN(configuredMaxWait)) {
DEBUG_BUILD &&
debug.warn('[React Router] lazyRouteTimeout must be a number, falling back to default:', defaultMaxWait);
_lazyRouteTimeout = defaultMaxWait;
} else if (configuredMaxWait < 0) {
DEBUG_BUILD &&
debug.warn(
'[React Router] lazyRouteTimeout must be non-negative or Infinity, got:',
configuredMaxWait,
'falling back to:',
defaultMaxWait,
);
_lazyRouteTimeout = defaultMaxWait;
} else {
_lazyRouteTimeout = configuredMaxWait;
}
_useEffect = useEffect;
_useLocation = useLocation;
_useNavigationType = useNavigationType;
_matchRoutes = matchRoutes;
_createRoutesFromChildren = createRoutesFromChildren;
_enableAsyncRouteHandlers = enableAsyncRouteHandlers;
_lazyRouteManifest = lazyRouteManifest;
// Initialize the router utils with the required dependencies
initializeRouterUtils(matchRoutes, stripBasename || false);
},
afterAllSetup(client) {
integration.afterAllSetup(client);
const initPathName = WINDOW.location?.pathname;
if (instrumentPageLoad && initPathName) {
startBrowserTracingPageLoadSpan(client, {
name: initPathName,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'pageload',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: `auto.pageload.react.reactrouter_v${version}`,
},
});
}
if (instrumentNavigation) {
CLIENTS_WITH_INSTRUMENT_NAVIGATION.add(client);
}
},
};
}
export function createV6CompatibleWrapUseRoutes(origUseRoutes: UseRoutes, version: V6CompatibleVersion): UseRoutes {
if (!_useEffect || !_useLocation || !_useNavigationType || !_matchRoutes) {
DEBUG_BUILD &&
debug.warn(
'reactRouterV6Instrumentation was unable to wrap `useRoutes` because of one or more missing parameters.',
);
return origUseRoutes;
}
const SentryRoutes: React.FC<{
children?: React.ReactNode;
routes: RouteObject[];
locationArg?: Partial<Location> | string;
}> = (props: { children?: React.ReactNode; routes: RouteObject[]; locationArg?: Partial<Location> | string }) => {
const isMountRenderPass = React.useRef(true);
const { routes, locationArg } = props;
const Routes = origUseRoutes(routes, locationArg);
const location = _useLocation();
const navigationType = _useNavigationType();
// A value with stable identity to either pick `locationArg` if available or `location` if not
const stableLocationParam =
typeof locationArg === 'string' || locationArg?.pathname ? (locationArg as { pathname: string }) : location;
_useEffect(() => {
const normalizedLocation =
typeof stableLocationParam === 'string' ? { pathname: stableLocationParam } : stableLocationParam;
if (isMountRenderPass.current) {
addRoutesToAllRoutes(routes);
updatePageloadTransaction({
activeRootSpan: getActiveRootSpan(),
location: normalizedLocation,
routes,
allRoutes: Array.from(allRoutes),
});
isMountRenderPass.current = false;
} else {
// Note: Component-based routes don't support lazy route tracking via lazyRouteTimeout
// because React.lazy() loads happen at the component level, not the router level.
// Use createBrowserRouter with patchRoutesOnNavigation for lazy route tracking.
handleNavigation({
location: normalizedLocation,
routes,
navigationType,
version,
allRoutes: Array.from(allRoutes),
});
}
}, [navigationType, stableLocationParam]);
return Routes;
};
// eslint-disable-next-line react/display-name
return (routes: RouteObject[], locationArg?: Partial<Location> | string): React.ReactElement | null => {
return <SentryRoutes routes={routes} locationArg={locationArg} />;
};
}
function wrapPatchRoutesOnNavigation(
opts: Record<string, unknown> | undefined,
isMemoryRouter = false,
capturedSpan?: Span,
): Record<string, unknown> {
if (!opts || !('patchRoutesOnNavigation' in opts) || typeof opts.patchRoutesOnNavigation !== 'function') {
return opts || {};
}
const originalPatchRoutes = opts.patchRoutesOnNavigation;
return {
...opts,
patchRoutesOnNavigation: async (args: unknown) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
const targetPath = (args as any)?.path;
// Use current active span if available, otherwise fall back to captured span (from router creation time).
// This ensures navigation spans use their own span (not the stale pageload span), while still
// supporting pageload spans that may have ended before patchRoutesOnNavigation is called.
const activeRootSpan = getActiveRootSpan() ?? capturedSpan;
if (!isMemoryRouter) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
const originalPatch = (args as any)?.patch;
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
const matches = (args as any)?.matches as Array<{ route: RouteObject }> | undefined;
if (originalPatch) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(args as any).patch = (routeId: string, children: RouteObject[]) => {
addRoutesToAllRoutes(children);
// Find the parent route from matches and attach children to it in allRoutes.
// React Router's patch attaches children to its internal route copies, but we need
// to update the route objects in our allRoutes Set for proper route matching.
if (matches && matches.length > 0) {
const leafMatch = matches[matches.length - 1];
const leafRoute = leafMatch?.route;
if (leafRoute) {
// Find the matching route in allRoutes by id, reference, or path
const matchingRoute = Array.from(allRoutes).find(route => {
const idMatches = route.id !== undefined && route.id === routeId;
const referenceMatches = route === leafRoute;
const pathMatches =
route.path !== undefined && leafRoute.path !== undefined && route.path === leafRoute.path;
return idMatches || referenceMatches || pathMatches;
});
if (matchingRoute) {
addResolvedRoutesToParent(children, matchingRoute);
}
}
}
// Use the captured activeRootSpan instead of getActiveRootSpan() to avoid race conditions
// where user navigates away during lazy route loading and we'd update the wrong span
const spanJson = activeRootSpan ? spanToJSON(activeRootSpan) : undefined;
// Only update if we have a valid targetPath (patchRoutesOnNavigation can be called without path),
// the captured span exists, hasn't ended, and is a navigation span
if (
targetPath &&
activeRootSpan &&
spanJson &&
!spanJson.timestamp && // Span hasn't ended yet
spanJson.op === 'navigation'
) {
updateNavigationSpan(
activeRootSpan,
{ pathname: targetPath, search: '', hash: '', state: null, key: 'default' },
Array.from(allRoutes),
true,
_matchRoutes,
);
}
return originalPatch(routeId, children);
};
}
}
const lazyLoadPromise = (async () => {
// Set context so async handlers can access correct targetPath and span
const contextToken = setNavigationContext(targetPath, activeRootSpan);
let result;
try {
result = await originalPatchRoutes(args);
} finally {
clearNavigationContext(contextToken);
// Resolve the deferred promise now that patchRoutesOnNavigation has completed.
// This ensures patchedEnd has waited long enough for the lazy routes to load.
if (activeRootSpan) {
resolveDeferredLazyRoutePromise(activeRootSpan);
}
}
// Use the captured activeRootSpan instead of getActiveRootSpan() to avoid race conditions
// where user navigates away during lazy route loading and we'd update the wrong span
const spanJson = activeRootSpan ? spanToJSON(activeRootSpan) : undefined;
if (
activeRootSpan &&
spanJson &&
!spanJson.timestamp && // Span hasn't ended yet
spanJson.op === 'navigation'
) {
// Use targetPath consistently - don't fall back to WINDOW.location which may have changed
// if the user navigated away during async loading
const pathname = targetPath;
if (pathname) {
updateNavigationSpan(
activeRootSpan,
{ pathname, search: '', hash: '', state: null, key: 'default' },
Array.from(allRoutes),
false,
_matchRoutes,
);
}
}
return result;
})();
if (activeRootSpan) {
trackLazyRouteLoad(activeRootSpan, lazyLoadPromise);
}
return lazyLoadPromise;
},
};
}
// eslint-disable-next-line complexity
export function handleNavigation(opts: {
location: Location;
routes: RouteObject[];
navigationType: Action;
version: V6CompatibleVersion;
matches?: AgnosticDataRouteMatch;
basename?: string;
allRoutes?: RouteObject[];
}): void {
const { location, routes, navigationType, version, matches, basename, allRoutes } = opts;
const branches = Array.isArray(matches) ? matches : _matchRoutes(allRoutes || routes, location, basename);
const client = getClient();
if (!client || !CLIENTS_WITH_INSTRUMENT_NAVIGATION.has(client)) {
return;
}
const activeRootSpan = getActiveRootSpan();
if (activeRootSpan && spanToJSON(activeRootSpan).op === 'pageload' && navigationType === 'POP') {
return;
}
if ((navigationType === 'PUSH' || navigationType === 'POP') && branches) {
const [name, source] = resolveRouteNameAndSource(
location,
allRoutes || routes,
allRoutes || routes,
branches as RouteMatch[],
basename,
_lazyRouteManifest,
_enableAsyncRouteHandlers,
);
const locationKey = computeLocationKey(location);
const trackedNav = activeNavigationSpans.get(client);
// Determine if this navigation should be skipped as a duplicate
const trackedSpanHasEnded =
trackedNav && !trackedNav.isPlaceholder ? !!spanToJSON(trackedNav.span).timestamp : false;
const { skip, shouldUpdate } = shouldSkipNavigation(trackedNav, locationKey, name, trackedSpanHasEnded);
if (skip) {
if (shouldUpdate && trackedNav) {
const oldName = trackedNav.routeName;
if (trackedNav.isPlaceholder) {
// Update placeholder's route name - the real span will be created with this name
trackedNav.routeName = name;
DEBUG_BUILD &&
debug.log(
`[Tracing] Updated placeholder navigation name from "${oldName}" to "${name}" (will apply to real span)`,
);
} else {
// Update existing real span from wildcard to parameterized route name
trackedNav.span.updateName(name);
trackedNav.span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, source as 'route' | 'url' | 'custom');
addNonEnumerableProperty(
trackedNav.span as { __sentry_navigation_name_set__?: boolean },
'__sentry_navigation_name_set__',
true,
);
trackedNav.routeName = name;
DEBUG_BUILD && debug.log(`[Tracing] Updated navigation span name from "${oldName}" to "${name}"`);
}