@@ -25,17 +25,27 @@ interface SentryEnhancedNextData extends NextData {
25
25
} ;
26
26
}
27
27
28
- // Author's note: It's really not that complicated.
29
- // eslint-disable-next-line complexity
28
+ /**
29
+ * Every Next.js page (static and dynamic ones) comes with a script tag with the id "__NEXT_DATA__". This script tag
30
+ * contains a JSON object with data that was either generated at build time for static pages (`getStaticProps`), or at
31
+ * runtime with data fetchers like `getServerSideProps.`.
32
+ *
33
+ * We can use this information to:
34
+ * - Always get the parameterized route we're in when loading a page.
35
+ * - Send trace information (trace-id, baggage) from the server to the client.
36
+ *
37
+ * This function extracts this information.
38
+ */
30
39
function extractNextDataTagInformation ( ) : {
31
- route : string ;
32
- source : 'route' | 'url' ;
40
+ route : string | undefined ;
33
41
traceId : string | undefined ;
34
42
baggage : string | undefined ;
35
43
params : ParsedUrlQuery | undefined ;
36
44
} {
37
45
let nextData : SentryEnhancedNextData | undefined ;
38
46
47
+ // Let's be on the safe side and actually check first if there is really a __NEXT_DATA__ script tag on the page.
48
+ // Theoretically this should always be the case though.
39
49
const nextDataTag = global . document . getElementById ( '__NEXT_DATA__' ) ;
40
50
if ( nextDataTag && nextDataTag . innerHTML ) {
41
51
try {
@@ -46,8 +56,7 @@ function extractNextDataTagInformation(): {
46
56
}
47
57
48
58
// `nextData.page` always contains the parameterized route
49
- const route = ( nextData || { } ) . page || global . document . location . pathname ;
50
- const source = nextData ? 'route' : 'url' ;
59
+ const route = ( nextData || { } ) . page ;
51
60
52
61
const getServerSidePropsTraceId = ( ( ( nextData || { } ) . props || { } ) . pageProps || { } ) . _sentryGetServerSidePropsTraceId ;
53
62
const getInitialPropsTraceId = ( ( nextData || { } ) . props || { } ) . _sentryGetInitialPropsTraceId ;
@@ -58,7 +67,6 @@ function extractNextDataTagInformation(): {
58
67
59
68
return {
60
69
route,
61
- source,
62
70
params,
63
71
// Ordering of the following shouldn't matter but `getInitialProps` generally runs before `getServerSideProps` so we give it priority.
64
72
traceId : getInitialPropsTraceId || getServerSidePropsTraceId ,
@@ -90,9 +98,10 @@ export function nextRouterInstrumentation(
90
98
startTransaction = startTransactionCb ;
91
99
92
100
if ( startTransactionOnPageLoad ) {
93
- const { route, source , traceId, baggage, params } = extractNextDataTagInformation ( ) ;
101
+ const { route, traceId, baggage, params } = extractNextDataTagInformation ( ) ;
94
102
95
- prevTransactionName = route ;
103
+ prevTransactionName = route || global . document . location . pathname ;
104
+ const source = route ? 'route' : 'url' ;
96
105
97
106
activeTransaction = startTransactionCb ( {
98
107
name : prevTransactionName ,
0 commit comments