|
| 1 | +import { hasTracingEnabled } from '@sentry/tracing'; |
| 2 | +import Document from 'next/document'; |
| 3 | + |
| 4 | +import { isBuild } from '../../utils/isBuild'; |
| 5 | +import { callTracedServerSideDataFetcher, withErrorInstrumentation } from './wrapperUtils'; |
| 6 | + |
| 7 | +type DocumentGetInitialProps = typeof Document.getInitialProps; |
| 8 | + |
| 9 | +/** |
| 10 | + * Create a wrapped version of the user's exported `getInitialProps` function in |
| 11 | + * a custom document ("_document.js"). |
| 12 | + * |
| 13 | + * @param origDocumentGetInitialProps The user's `getInitialProps` function |
| 14 | + * @param parameterizedRoute The page's parameterized route |
| 15 | + * @returns A wrapped version of the function |
| 16 | + */ |
| 17 | +export function withSentryServerSideDocumentGetInitialProps( |
| 18 | + origDocumentGetInitialProps: DocumentGetInitialProps, |
| 19 | +): DocumentGetInitialProps { |
| 20 | + return async function ( |
| 21 | + ...documentGetInitialPropsArguments: Parameters<DocumentGetInitialProps> |
| 22 | + ): ReturnType<DocumentGetInitialProps> { |
| 23 | + if (isBuild()) { |
| 24 | + return origDocumentGetInitialProps(...documentGetInitialPropsArguments); |
| 25 | + } |
| 26 | + |
| 27 | + const [context] = documentGetInitialPropsArguments; |
| 28 | + const { req, res } = context; |
| 29 | + |
| 30 | + const errorWrappedGetInitialProps = withErrorInstrumentation(origDocumentGetInitialProps); |
| 31 | + |
| 32 | + if (hasTracingEnabled()) { |
| 33 | + // Since this wrapper is only applied to `getInitialProps` running on the server, we can assert that `req` and |
| 34 | + // `res` are always defined: https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#context-object |
| 35 | + return callTracedServerSideDataFetcher( |
| 36 | + errorWrappedGetInitialProps, |
| 37 | + documentGetInitialPropsArguments, |
| 38 | + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 39 | + req!, |
| 40 | + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 41 | + res!, |
| 42 | + { |
| 43 | + dataFetcherRouteName: '/_document', |
| 44 | + requestedRouteName: context.pathname, |
| 45 | + dataFetchingMethodName: 'getInitialProps', |
| 46 | + }, |
| 47 | + ); |
| 48 | + } else { |
| 49 | + return errorWrappedGetInitialProps(...documentGetInitialPropsArguments); |
| 50 | + } |
| 51 | + }; |
| 52 | +} |
0 commit comments