apiWrapperTemplate.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import * as Sentry from '@sentry/nextjs';
  2. import * as serverComponentModule from '__SENTRY_WRAPPING_TARGET_FILE__';
  3. export * from '__SENTRY_WRAPPING_TARGET_FILE__';
  4. /*
  5. * This file is a template for the code which will be substituted when our webpack loader handles API files in the
  6. * `pages/` directory.
  7. *
  8. * We use `__SENTRY_WRAPPING_TARGET_FILE__` as a placeholder for the path to the file being wrapped. Because it's not a real package,
  9. * this causes both TS and ESLint to complain, hence the pragma comments below.
  10. */
  11. const userApiModule = serverComponentModule ;
  12. // Default to undefined. It's possible for Next.js users to not define any exports/handlers in an API route. If that is
  13. // the case Next.js wil crash during runtime but the Sentry SDK should definitely not crash so we need tohandle it.
  14. let userProvidedHandler = undefined;
  15. if ('default' in userApiModule && typeof userApiModule.default === 'function') {
  16. // Handle when user defines via ESM export: `export default myFunction;`
  17. userProvidedHandler = userApiModule.default;
  18. } else if (typeof userApiModule === 'function') {
  19. // Handle when user defines via CJS export: "module.exports = myFunction;"
  20. userProvidedHandler = userApiModule;
  21. }
  22. const origConfig = userApiModule.config || {};
  23. // Setting `externalResolver` to `true` prevents nextjs from throwing a warning in dev about API routes resolving
  24. // without sending a response. It's a false positive (a response is sent, but only after we flush our send queue), and
  25. // we throw a warning of our own to tell folks that, but it's better if we just don't have to deal with it in the first
  26. // place.
  27. const config = {
  28. ...origConfig,
  29. api: {
  30. ...origConfig.api,
  31. externalResolver: true,
  32. },
  33. };
  34. let wrappedHandler = userProvidedHandler;
  35. if (wrappedHandler) {
  36. wrappedHandler = Sentry.wrapApiHandlerWithSentry(wrappedHandler, '__ROUTE__');
  37. }
  38. if (wrappedHandler && __VERCEL_CRONS_CONFIGURATION__) {
  39. wrappedHandler = Sentry.wrapApiHandlerWithSentryVercelCrons(wrappedHandler, __VERCEL_CRONS_CONFIGURATION__);
  40. }
  41. const wrappedHandler$1 = wrappedHandler;
  42. export { config, wrappedHandler$1 as default };