Skip to content

Commit 7316b85

Browse files
authored
fix(nextjs): Exclude SDK from Edge runtime bundles (#6683)
1 parent 1b4d9da commit 7316b85

File tree

6 files changed

+40
-45
lines changed

6 files changed

+40
-45
lines changed

packages/nextjs/src/config/loaders/proxyLoader.ts

+7
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ type LoaderOptions = {
99
pagesDir: string;
1010
pageExtensionRegex: string;
1111
excludeServerRoutes: Array<RegExp | string>;
12+
isEdgeRuntime: boolean;
1213
};
1314

1415
/**
@@ -22,8 +23,14 @@ export default async function proxyLoader(this: LoaderThis<LoaderOptions>, userC
2223
pagesDir,
2324
pageExtensionRegex,
2425
excludeServerRoutes = [],
26+
isEdgeRuntime,
2527
} = 'getOptions' in this ? this.getOptions() : this.query;
2628

29+
// We currently don't support the edge runtime
30+
if (isEdgeRuntime) {
31+
return userCode;
32+
}
33+
2734
// Get the parameterized route name from this page's filepath
2835
const parameterizedRoute = path
2936
// Get the path of the file insde of the pages directory

packages/nextjs/src/config/templates/apiProxyLoaderTemplate.ts

+2-16
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ type NextApiModule = (
2323
}
2424
// CJS export
2525
| NextApiHandler
26-
) & { config?: PageConfig & { runtime?: string } };
26+
) & { config?: PageConfig };
2727

2828
const userApiModule = origModule as NextApiModule;
2929

@@ -53,21 +53,7 @@ export const config = {
5353
},
5454
};
5555

56-
// This is a variable that Next.js will string replace during build with a string if run in an edge runtime from Next.js
57-
// v12.2.1-canary.3 onwards:
58-
// https://github.com/vercel/next.js/blob/166e5fb9b92f64c4b5d1f6560a05e2b9778c16fb/packages/next/build/webpack-config.ts#L206
59-
// https://edge-runtime.vercel.sh/features/available-apis#addressing-the-runtime
60-
declare const EdgeRuntime: string | undefined;
61-
62-
let exportedHandler;
63-
64-
if (typeof EdgeRuntime === 'string') {
65-
exportedHandler = userProvidedHandler;
66-
} else {
67-
exportedHandler = userProvidedHandler ? Sentry.withSentryAPI(userProvidedHandler, '__ROUTE__') : undefined;
68-
}
69-
70-
export default exportedHandler;
56+
export default userProvidedHandler ? Sentry.withSentryAPI(userProvidedHandler, '__ROUTE__') : undefined;
7157

7258
// Re-export anything exported by the page module we're wrapping. When processing this code, Rollup is smart enough to
7359
// not include anything whose name matchs something we've explicitly exported above.

packages/nextjs/src/config/types.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ export type BuildContext = {
137137
// eslint-disable-next-line @typescript-eslint/no-explicit-any
138138
defaultLoaders: any;
139139
totalPages: number;
140-
nextRuntime?: 'nodejs' | 'edge';
140+
nextRuntime?: 'nodejs' | 'edge'; // Added in Next.js 12+
141141
};
142142

143143
/**

packages/nextjs/src/config/webpack.ts

+30-2
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,13 @@ export function constructWebpackConfigFunction(
8585
// Add a loader which will inject code that sets global values
8686
addValueInjectionLoader(newConfig, userNextConfig, userSentryOptions);
8787

88+
if (buildContext.nextRuntime === 'edge') {
89+
// eslint-disable-next-line no-console
90+
console.warn(
91+
'[@sentry/nextjs] You are using edge functions or middleware. Please note that Sentry does not yet support error monitoring for these features.',
92+
);
93+
}
94+
8895
if (isServer) {
8996
if (userSentryOptions.autoInstrumentServerFunctions !== false) {
9097
const pagesDir = newConfig.resolve?.alias?.['private-next-pages'] as string;
@@ -102,6 +109,7 @@ export function constructWebpackConfigFunction(
102109
pagesDir,
103110
pageExtensionRegex,
104111
excludeServerRoutes: userSentryOptions.excludeServerRoutes,
112+
isEdgeRuntime: buildContext.nextRuntime === 'edge',
105113
},
106114
},
107115
],
@@ -305,7 +313,15 @@ async function addSentryToEntryProperty(
305313

306314
// inject into all entry points which might contain user's code
307315
for (const entryPointName in newEntryProperty) {
308-
if (shouldAddSentryToEntryPoint(entryPointName, isServer, userSentryOptions.excludeServerRoutes, isDev)) {
316+
if (
317+
shouldAddSentryToEntryPoint(
318+
entryPointName,
319+
isServer,
320+
userSentryOptions.excludeServerRoutes,
321+
isDev,
322+
buildContext.nextRuntime === 'edge',
323+
)
324+
) {
309325
addFilesToExistingEntryPoint(newEntryProperty, entryPointName, filesToInject);
310326
} else {
311327
if (
@@ -432,7 +448,13 @@ function shouldAddSentryToEntryPoint(
432448
isServer: boolean,
433449
excludeServerRoutes: Array<string | RegExp> = [],
434450
isDev: boolean,
451+
isEdgeRuntime: boolean,
435452
): boolean {
453+
// We don't support the Edge runtime yet
454+
if (isEdgeRuntime) {
455+
return false;
456+
}
457+
436458
// On the server side, by default we inject the `Sentry.init()` code into every page (with a few exceptions).
437459
if (isServer) {
438460
const entryPointRoute = entryPointName.replace(/^pages/, '');
@@ -529,7 +551,13 @@ export function getWebpackPluginOptions(
529551
stripPrefix: ['webpack://_N_E/'],
530552
urlPrefix,
531553
entries: (entryPointName: string) =>
532-
shouldAddSentryToEntryPoint(entryPointName, isServer, userSentryOptions.excludeServerRoutes, isDev),
554+
shouldAddSentryToEntryPoint(
555+
entryPointName,
556+
isServer,
557+
userSentryOptions.excludeServerRoutes,
558+
isDev,
559+
buildContext.nextRuntime === 'edge',
560+
),
533561
release: getSentryRelease(buildId),
534562
dryRun: isDev,
535563
});

packages/nextjs/src/index.client.ts

-15
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import { RewriteFrames } from '@sentry/integrations';
22
import { configureScope, init as reactInit, Integrations } from '@sentry/react';
33
import { BrowserTracing, defaultRequestInstrumentationOptions, hasTracingEnabled } from '@sentry/tracing';
44
import { EventProcessor } from '@sentry/types';
5-
import { logger } from '@sentry/utils';
65

76
import { nextRouterInstrumentation } from './performance/client';
87
import { buildMetadata } from './utils/metadata';
@@ -31,26 +30,12 @@ export { BrowserTracing };
3130
// Treeshakable guard to remove all code related to tracing
3231
declare const __SENTRY_TRACING__: boolean;
3332

34-
// This is a variable that Next.js will string replace during build with a string if run in an edge runtime from Next.js
35-
// v12.2.1-canary.3 onwards:
36-
// https://github.com/vercel/next.js/blob/166e5fb9b92f64c4b5d1f6560a05e2b9778c16fb/packages/next/build/webpack-config.ts#L206
37-
// https://edge-runtime.vercel.sh/features/available-apis#addressing-the-runtime
38-
declare const EdgeRuntime: string | undefined;
39-
4033
const globalWithInjectedValues = global as typeof global & {
4134
__rewriteFramesAssetPrefixPath__: string;
4235
};
4336

4437
/** Inits the Sentry NextJS SDK on the browser with the React SDK. */
4538
export function init(options: NextjsOptions): void {
46-
if (typeof EdgeRuntime === 'string') {
47-
// If the SDK is imported when using the Vercel Edge Runtime, it will import the browser SDK, even though it is
48-
// running the server part of a Next.js application. We can use the `EdgeRuntime` to check for that case and make
49-
// the init call a no-op. This will prevent the SDK from crashing on the Edge Runtime.
50-
__DEBUG_BUILD__ && logger.log('Vercel Edge Runtime detected. Will not initialize SDK.');
51-
return;
52-
}
53-
5439
applyTunnelRouteOption(options);
5540
buildMetadata(options, ['nextjs', 'react']);
5641
options.environment = options.environment || process.env.NODE_ENV;

packages/nextjs/src/index.server.ts

-11
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,6 @@ const globalWithInjectedValues = global as typeof global & {
3030

3131
const domain = domainModule as typeof domainModule & { active: (domainModule.Domain & Carrier) | null };
3232

33-
// This is a variable that Next.js will string replace during build with a string if run in an edge runtime from Next.js
34-
// v12.2.1-canary.3 onwards:
35-
// https://github.com/vercel/next.js/blob/166e5fb9b92f64c4b5d1f6560a05e2b9778c16fb/packages/next/build/webpack-config.ts#L206
36-
// https://edge-runtime.vercel.sh/features/available-apis#addressing-the-runtime
37-
declare const EdgeRuntime: string | undefined;
38-
3933
// Exporting this constant means we can compute it without the linter complaining, even if we stop directly using it in
4034
// this file. It's important that it be computed as early as possible, because one of its indicators is seeing 'build'
4135
// (as in the CLI command `next build`) in `process.argv`. Later on in the build process, everything's been spun out
@@ -51,11 +45,6 @@ export function init(options: NextjsOptions): void {
5145
logger.enable();
5246
}
5347

54-
if (typeof EdgeRuntime === 'string') {
55-
__DEBUG_BUILD__ && logger.log('Vercel Edge Runtime detected. Will not initialize SDK.');
56-
return;
57-
}
58-
5948
__DEBUG_BUILD__ && logger.log('Initializing SDK...');
6049

6150
if (sdkAlreadyInitialized()) {

0 commit comments

Comments
 (0)