From f1259d97cbe8aa9a0cd30d10c4ca6d780d3cdc0e Mon Sep 17 00:00:00 2001 From: Katie Byers Date: Mon, 14 Nov 2022 23:02:56 -0800 Subject: [PATCH] inject sentry into all serverside entrypoints besides `_app` and `_document` --- packages/nextjs/src/config/webpack.ts | 37 ++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/packages/nextjs/src/config/webpack.ts b/packages/nextjs/src/config/webpack.ts index 52a48e8d04f9..93fb77899d78 100644 --- a/packages/nextjs/src/config/webpack.ts +++ b/packages/nextjs/src/config/webpack.ts @@ -379,12 +379,37 @@ function checkWebpackPluginOverrides( * @param isServer Whether or not this function is being called in the context of a server build * @returns `true` if sentry code should be injected, and `false` otherwise */ -function shouldAddSentryToEntryPoint(entryPointName: string, isServer: boolean): boolean { - return ( - entryPointName === 'pages/_app' || - (entryPointName.includes('pages/api') && !entryPointName.includes('_middleware')) || - (isServer && entryPointName === 'pages/_error') - ); +function shouldAddSentryToEntryPoint( + entryPointName: string, + isServer: boolean, +): boolean { + // On the server side, by default we inject the `Sentry.init()` code into every page (with a few exceptions). + if (isServer) { + const entryPointRoute = entryPointName.replace(/^pages/, ''); + if ( + // All non-API pages contain both of these components, and we don't want to inject more than once, so as long as + // we're doing the individual pages, it's fine to skip these + entryPointRoute === '/_app' || + entryPointRoute === '/_document' || + // While middleware was in beta, it could be anywhere (at any level) in the `pages` directory, and would be called + // `_middleware.js`. Until the SDK runs successfully in the lambda edge environment, we have to exclude these. + entryPointName.includes('_middleware') || + // In case anything else weird ends up in there + !entryPointName.startsWith('pages/') + ) { + return false; + } + + // We want to inject Sentry into all other pages + return true; + } + + // On the client side, we only want to inject into `_app`, because that guarantees there'll be only one copy of the + // SDK in the eventual bundle. Since `_app` is the (effectively) the root component for every nextjs app, inclusing + // Sentry there means it will be available for every front end page. + else { + return entryPointName === 'pages/_app'; + } } /**