11import { RewriteFrames } from '@sentry/integrations' ;
22import { configureScope , getCurrentHub , init as nodeInit , Integrations } from '@sentry/node' ;
3- import { logger } from '@sentry/utils' ;
3+ import { escapeStringForRegex , logger } from '@sentry/utils' ;
4+ import * as path from 'path' ;
45
56import { instrumentServer } from './utils/instrumentServer' ;
67import { MetadataBuilder } from './utils/metadataBuilder' ;
@@ -29,7 +30,6 @@ export function init(options: NextjsOptions): void {
2930 const metadataBuilder = new MetadataBuilder ( options , [ 'nextjs' , 'node' ] ) ;
3031 metadataBuilder . addSdkMetadata ( ) ;
3132 options . environment = options . environment || process . env . NODE_ENV ;
32- // TODO capture project root and store in an env var for RewriteFrames?
3333 addServerIntegrations ( options ) ;
3434 // Right now we only capture frontend sessions for Next.js
3535 options . autoSessionTracking = false ;
@@ -47,25 +47,29 @@ function sdkAlreadyInitialized(): boolean {
4747 return ! ! hub . getClient ( ) ;
4848}
4949
50- const SOURCEMAP_FILENAME_REGEX = / ^ .* \/ \. n e x t \/ / ;
51-
52- const defaultRewriteFramesIntegration = new RewriteFrames ( {
53- iteratee : frame => {
54- frame . filename = frame . filename ?. replace ( SOURCEMAP_FILENAME_REGEX , 'app:///_next/' ) ;
55- return frame ;
56- } ,
57- } ) ;
58-
59- const defaultHttpTracingIntegration = new Integrations . Http ( { tracing : true } ) ;
60-
6150function addServerIntegrations ( options : NextjsOptions ) : void {
51+ // This value is injected at build time, based on the output directory specified in the build config
52+ const distDirName = ( global as typeof global & { __rewriteFramesDistDir__ : string } ) . __rewriteFramesDistDir__ ;
53+ // nextjs always puts the build directory at the project root level, which is also where you run `next start` from, so
54+ // we can read in the project directory from the currently running process
55+ const distDirAbsPath = path . resolve ( process . cwd ( ) , distDirName ) ;
56+ const SOURCEMAP_FILENAME_REGEX = new RegExp ( escapeStringForRegex ( distDirAbsPath ) ) ;
57+
58+ const defaultRewriteFramesIntegration = new RewriteFrames ( {
59+ iteratee : frame => {
60+ frame . filename = frame . filename ?. replace ( SOURCEMAP_FILENAME_REGEX , 'app:///_next' ) ;
61+ return frame ;
62+ } ,
63+ } ) ;
64+
6265 if ( options . integrations ) {
6366 options . integrations = addIntegration ( defaultRewriteFramesIntegration , options . integrations ) ;
6467 } else {
6568 options . integrations = [ defaultRewriteFramesIntegration ] ;
6669 }
6770
6871 if ( options . tracesSampleRate !== undefined || options . tracesSampler !== undefined ) {
72+ const defaultHttpTracingIntegration = new Integrations . Http ( { tracing : true } ) ;
6973 options . integrations = addIntegration ( defaultHttpTracingIntegration , options . integrations , {
7074 Http : { keyPath : '_tracing' , value : true } ,
7175 } ) ;
0 commit comments