perf: dynamically import sentry in Next.js api routes' wrapper (#23710)

* dynamically import sentry in nextjs api routes wrapper

* refactor

* same for pages router

* fixes

* address feedback

* refactor

* address feedback
This commit is contained in:
Benny Joo
2025-09-30 02:13:50 +05:30
committed by GitHub
parent 61c44780f0
commit 0055dd1142
2 changed files with 18 additions and 11 deletions
@@ -1,5 +1,3 @@
import { wrapApiHandlerWithSentry } from "@sentry/nextjs";
import { captureException } from "@sentry/nextjs";
import type { Params } from "app/_types";
import { ApiError } from "next/dist/server/api-utils";
import type { NextRequest } from "next/server";
@@ -21,10 +19,13 @@ export const defaultResponderForAppDir = <T extends NextResponse | Response = Ne
let ok = false;
try {
performance.mark("Start");
const result = endpointRoute
? await wrapApiHandlerWithSentry(async () => await handler(req, { params }), endpointRoute)()
: await handler(req, { params });
let result: T | undefined;
if (process.env.NODE_ENV === "development" || !endpointRoute) {
result = await handler(req, { params });
} else {
const { wrapApiHandlerWithSentry } = await import("@sentry/nextjs");
result = await wrapApiHandlerWithSentry(async () => await handler(req, { params }), endpointRoute)();
}
ok = true;
if (result) {
@@ -49,6 +50,7 @@ export const defaultResponderForAppDir = <T extends NextResponse | Response = Ne
// Don't report 400-499 errors to Sentry/console
if (!(serverError.statusCode >= 400 && serverError.statusCode < 500)) {
console.error(serverError);
const { captureException } = await import("@sentry/nextjs");
captureException(error);
}
+10 -5
View File
@@ -1,5 +1,3 @@
import { wrapApiHandlerWithSentry } from "@sentry/nextjs";
import { captureException } from "@sentry/nextjs";
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerErrorFromUnknown } from "./getServerErrorFromUnknown";
@@ -17,9 +15,15 @@ export function defaultResponder<T>(
let ok = false;
try {
performance.mark("Start");
const result = endpointRoute
? await wrapApiHandlerWithSentry(f, endpointRoute)(req, res)
: await f(req, res);
let result: T | undefined;
if (process.env.NODE_ENV === "development" || !endpointRoute) {
result = await f(req, res);
} else {
const { wrapApiHandlerWithSentry } = await import("@sentry/nextjs");
result = await wrapApiHandlerWithSentry(f, endpointRoute)(req, res);
}
ok = true;
if (result && !res.writableEnded) {
return res.json(result);
@@ -29,6 +33,7 @@ export function defaultResponder<T>(
// we don't want to report Bad Request errors to Sentry / console
if (!(error.statusCode >= 400 && error.statusCode < 500)) {
console.error(error);
const { captureException } = await import("@sentry/nextjs");
captureException(error);
}
return res