@@ -6,7 +6,6 @@ import { escapeStringForRegex, logger } from '@sentry/utils';
66import * as domainModule from 'domain' ;
77import * as path from 'path' ;
88
9- import { instrumentServer } from './utils/instrumentServer' ;
109import { MetadataBuilder } from './utils/metadataBuilder' ;
1110import { NextjsOptions } from './utils/nextjsOptions' ;
1211import { addIntegration } from './utils/userIntegrations' ;
@@ -20,6 +19,17 @@ export { ErrorBoundary, withErrorBoundary } from '@sentry/react';
2019type GlobalWithDistDir = typeof global & { __rewriteFramesDistDir__ : string } ;
2120const domain = domainModule as typeof domainModule & { active : ( domainModule . Domain & Carrier ) | null } ;
2221
22+ // During build, the main process is invoked by
23+ // `node next build`
24+ // and child processes are invoked as
25+ // `node <path>/node_modules/jest-worker/build/workers/processChild.js`,
26+ // whereas at runtime the process is invoked as
27+ // `node next start`
28+ // or
29+ // `node /var/runtime/index.js`.
30+ const isBuild = new RegExp ( 'build' ) . test ( process . argv . toString ( ) ) ;
31+ const isVercel = ! ! process . env . VERCEL ;
32+
2333/** Inits the Sentry NextJS SDK on node. */
2434export function init ( options : NextjsOptions ) : void {
2535 if ( options . debug ) {
@@ -54,7 +64,7 @@ export function init(options: NextjsOptions): void {
5464
5565 configureScope ( scope => {
5666 scope . setTag ( 'runtime' , 'node' ) ;
57- if ( process . env . VERCEL ) {
67+ if ( isVercel ) {
5868 scope . setTag ( 'vercel' , true ) ;
5969 }
6070
@@ -119,5 +129,24 @@ function filterTransactions(event: Event): Event | null {
119129export { withSentryConfig } from './config' ;
120130export { withSentry } from './utils/withSentry' ;
121131
122- // wrap various server methods to enable error monitoring and tracing
123- instrumentServer ( ) ;
132+ // Wrap various server methods to enable error monitoring and tracing. (Note: This only happens for non-Vercel
133+ // deployments, because the current method of doing the wrapping a) crashes Next 12 apps deployed to Vercel and
134+ // b) doesn't work on those apps anyway. We also don't do it during build, because there's no server running in that
135+ // phase.)
136+ if ( ! isVercel && ! isBuild ) {
137+ // Dynamically require the file because even importing from it causes Next 12 to crash on Vercel.
138+ // In environments where the JS file doesn't exist, such as testing, import the TS file.
139+ try {
140+ // eslint-disable-next-line @typescript-eslint/no-var-requires
141+ const { instrumentServer } = require ( './utils/instrumentServer.js' ) ;
142+ instrumentServer ( ) ;
143+ } catch {
144+ try {
145+ // eslint-disable-next-line @typescript-eslint/no-var-requires
146+ const { instrumentServer } = require ( './utils/instrumentServer.ts' ) ;
147+ instrumentServer ( ) ;
148+ } catch {
149+ // Server not instrumented. Not adding logs to avoid noise.
150+ }
151+ }
152+ }
0 commit comments