| 
 | 1 | +import { formatAsCode, nextLogger } from '../../utils/nextLogger';  | 
 | 2 | +// We import these types from `withSentry` rather than directly from `next` because our version can work simultaneously  | 
 | 3 | +// with multiple versions of next. See note in `withSentry` for more.  | 
 | 4 | +import type { NextApiHandler, WrappedNextApiHandler } from '../../utils/withSentry';  | 
 | 5 | +import { withSentry } from '../../utils/withSentry';  | 
 | 6 | + | 
 | 7 | +/**  | 
 | 8 | + * Wrap the given API route handler for tracing and error capturing. Thin wrapper around `withSentry`, which only  | 
 | 9 | + * applies it if it hasn't already been applied.  | 
 | 10 | + *  | 
 | 11 | + * @param maybeWrappedHandler The handler exported from the user's API page route file, which may or may not already be  | 
 | 12 | + * wrapped with `withSentry`  | 
 | 13 | + * @param parameterizedRoute The page's route, passed in via the proxy loader  | 
 | 14 | + * @returns The wrapped handler  | 
 | 15 | + */  | 
 | 16 | +export function withSentryAPI(  | 
 | 17 | +  maybeWrappedHandler: NextApiHandler | WrappedNextApiHandler,  | 
 | 18 | +  parameterizedRoute: string,  | 
 | 19 | +): WrappedNextApiHandler {  | 
 | 20 | +  // Log a warning if the user is still manually wrapping their route in `withSentry`. Doesn't work in cases where  | 
 | 21 | +  // there's been an intermediate wrapper (like `withSentryAPI(someOtherWrapper(withSentry(handler)))`) but should catch  | 
 | 22 | +  // most cases. Only runs once per route. (Note: Such double-wrapping isn't harmful, but we'll eventually deprecate and remove `withSentry`, so  | 
 | 23 | +  // best to get people to stop using it.)  | 
 | 24 | +  if (maybeWrappedHandler.name === 'sentryWrappedHandler') {  | 
 | 25 | +    const [_sentryNextjs_, _autoWrapOption_, _withSentry_, _route_] = [  | 
 | 26 | +      '@sentry/nextjs',  | 
 | 27 | +      'autoInstrumentServerFunctions',  | 
 | 28 | +      'withSentry',  | 
 | 29 | +      parameterizedRoute,  | 
 | 30 | +    ].map(phrase => formatAsCode(phrase));  | 
 | 31 | + | 
 | 32 | +    nextLogger.info(  | 
 | 33 | +      `${_sentryNextjs_} is running with the ${_autoWrapOption_} flag set, which means API routes no longer need to ` +  | 
 | 34 | +        `be manually wrapped with ${_withSentry_}. Detected manual wrapping in ${_route_}.`,  | 
 | 35 | +    );  | 
 | 36 | +  }  | 
 | 37 | + | 
 | 38 | +  return withSentry(maybeWrappedHandler, parameterizedRoute);  | 
 | 39 | +}  | 
0 commit comments