@sentry/nextjs
Version:
Official Sentry SDK for Next.js
80 lines (77 loc) • 2.92 kB
JavaScript
import { withIsolationScope, getCurrentScope, winterCGRequestToRequestData, getActiveSpan, getRootSpan, setCapturedScopesOnSpan, startSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, handleCallbackErrors, captureException } from '@sentry/core';
import { waitUntil, flushSafelyWithTimeout } from './utils/responseEnd.js';
import { isPathnameUnderSentryTunnelRoute } from './utils/tunnelPathnameMatch.js';
function wrapMiddlewareWithSentry(middleware) {
return new Proxy(middleware, {
apply: async (wrappingTarget, thisArg, args) => {
const tunnelRoute = "_sentryRewritesTunnelPath" in globalThis ? globalThis._sentryRewritesTunnelPath : void 0;
if (tunnelRoute && typeof tunnelRoute === "string") {
const req = args[0];
if (req instanceof Request) {
const url = new URL(req.url);
const isTunnelRequest = isPathnameUnderSentryTunnelRoute(url.pathname, tunnelRoute);
if (isTunnelRequest) {
return new Response(null, {
status: 200,
headers: {
"x-middleware-next": "1"
}
});
}
}
}
return withIsolationScope((isolationScope) => {
const req = args[0];
const currentScope = getCurrentScope();
let spanName;
let spanSource;
if (req instanceof Request) {
isolationScope.setSDKProcessingMetadata({
normalizedRequest: winterCGRequestToRequestData(req)
});
spanName = `middleware ${req.method}`;
spanSource = "url";
} else {
spanName = "middleware";
spanSource = "component";
}
currentScope.setTransactionName(spanName);
const runMiddleware = () => handleCallbackErrors(
() => wrappingTarget.apply(thisArg, args),
(error) => {
captureException(error, {
mechanism: {
type: "auto.function.nextjs.wrap_middleware",
handled: false
}
});
},
() => {
waitUntil(flushSafelyWithTimeout());
}
);
const activeSpan = getActiveSpan();
if (activeSpan) {
const rootSpan = getRootSpan(activeSpan);
if (rootSpan) {
setCapturedScopesOnSpan(rootSpan, currentScope, isolationScope);
}
return runMiddleware();
}
return startSpan(
{
name: spanName,
op: "http.server.middleware",
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: spanSource,
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.function.nextjs.wrap_middleware"
}
},
runMiddleware
);
});
}
});
}
export { wrapMiddlewareWithSentry };
//# sourceMappingURL=wrapMiddlewareWithSentry.js.map