Skip to content

@sentry/nextjs not reporting errors in next.js api routes #6450

Closed
@Jay-flow

Description

@Jay-flow

Version

@sentry/nextjs: 7.23.0
next: 13.0.6

Issue

@sentry/nextjs not reporting errors in next.js api routes
Only errors from the font-end are reported to Sentry.

Do not report API errors to Sentry.

pages/api/test.ts

import { withSentry } from "@sentry/nextjs"
import { OK } from "http-status"
import { NextApiRequest, NextApiResponse } from "next"

const handle = async (req: NextApiRequest, res: NextApiResponse) => {
  throw new Error("API Test 1")

  return res.status(OK).end()
}

export default withSentry(handle)

I completed the setting according to the guide.

Below are the files I set up.
sentry.client.config.ts

import * as Sentry from "@sentry/nextjs"

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  tracesSampleRate: 1.0,
})

sentry.server.config.ts

import * as Sentry from "@sentry/nextjs"

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  tracesSampleRate: 1.0,
  debug: true,
})

next.config.js

/** @type {import('next').NextConfig} */
const { withSentryConfig } = require("@sentry/nextjs")

const securityHeaders = [
  {
    key: "X-XSS-Protection",
    value: "1; mode=block",
  },
]

const nextConfig = {
  reactStrictMode: false,
  sentry: {
    hideSourceMaps: true,
  },
  webpack: (config) => {
    if (!config.experiments) {
      config.experiments = {}
    }

    config.experiments.topLevelAwait = true
    config.resolve.fallback = {
      ...config.resolve.fallback,
      fs: false,
    }

    return config
  },
 async headers() {
    return [
      {
        source: "/:path*",
        headers: securityHeaders,
      },
    ]
  },
}

module.exports = withSentryConfig(nextConfig, {
  // silent: true,
})

pages/_error.tsx

/**
 * NOTE: This requires `@sentry/nextjs` version 7.3.0 or higher.
 *
 * This page is loaded by Nextjs:
 *  - on the server, when data-fetching methods throw or reject
 *  - on the client, when `getInitialProps` throws or rejects
 *  - on the client, when a React lifecycle method throws or rejects, and it's
 *    caught by the built-in Nextjs error boundary
 *
 * See:
 *  - https://nextjs.org/docs/basic-features/data-fetching/overview
 *  - https://nextjs.org/docs/api-reference/data-fetching/get-initial-props
 *  - https://reactjs.org/docs/error-boundaries.html
 */

import * as Sentry from "@sentry/nextjs"
import type { NextPage } from "next"
import type { ErrorProps } from "next/error"
import NextErrorComponent from "next/error"

const CustomErrorComponent: NextPage<ErrorProps> = (props) => {
  // If you're using a Nextjs version prior to 12.2.1, uncomment this to
  // compensate for https://github.com/vercel/next.js/issues/8592
  // Sentry.captureUnderscoreErrorException(props);

  return <NextErrorComponent statusCode={props.statusCode} />
}

CustomErrorComponent.getInitialProps = async (contextData) => {
  // In case this is running in a serverless function, await this in order to give Sentry
  // time to send the error before the lambda exits
  await Sentry.captureUnderscoreErrorException(contextData)

  // This will contain the status code of the response
  return NextErrorComponent.getInitialProps(contextData)
}

export default CustomErrorComponent

.sentryclirc

[auth]
token=xxxxxxxxxxxxxxx

sentry.prooperties

defaults.url=https://sentry.io/
defaults.org=xxxx
defaults.project=javascript-nextjs
cli.executable=node_modules/@sentry/cli/bin/sentry-cli

Below is the log displayed on the console.

info  - @sentry/nextjs is running with the autoInstrumentServerFunctions flag set, which means API routes no longer need to be manually wrapped with withSentry. Detected manual wrapping in /api/test.
wait  - compiling /_error (client and server)...
error - pages/api/test.ts (6:8) @ handle
error - Error: API Test 1
    at handle (webpack-internal:///(api)/./pages/api/test.ts?__sentry_wrapped__:12:11)
    at sentryWrappedHandler (/Users/asdf/Projects/test-web/node_modules/@sentry/nextjs/cjs/config/wrappers/withSentryAPI.js:62:14)
    at /Users/asdfProjects/test-web/node_modules/@sentry/nextjs/cjs/config/wrappers/withSentryAPI.js:132:37
    at bound (node:domain:433:15)
    at runBound (node:domain:444:12)
    at sentryWrappedHandler (/Users/asdf/Projects/test-web/node_modules/@sentry/nextjs/cjs/config/wrappers/withSentryAPI.js:196:12)
    at Object.apiResolver (/Users/asdf/Projects/test-web/node_modules/next/dist/server/api-utils/node.js:363:15)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async DevServer.runApi (/Users/asdf/Projects/test-web/node_modules/next/dist/server/next-server.js:474:9) {
  page: '/api/test'
}
  4 | 
  5 | const handle = async (req: NextApiRequest, res: NextApiResponse) => {
> 6 |   throw new Error("API Test 1")
    |        ^
  7 | 
  8 |   return res.status(OK).end()
  9 | }
[Sentry Webpack Plugin] Creating new release:
 'development'
[Sentry Webpack Plugin] Calling upload-sourcemaps with:
 {
  finalize: true,
  rewrite: true,
  include: [
    {
      paths: [
        '/Users/asdf/Projects/test-web/.next/static/chunks/pages'
      ],
      urlPrefix: '~/_next/static/chunks/pages'
    }
  ],
  ignore: [],
  configFile: 'sentry.properties',
  stripPrefix: [ 'webpack://_N_E/' ],
  urlPrefix: '~/_next',
  entries: [Function: entries],
  release: 'development',
  dryRun: true
}
[Sentry Webpack Plugin] Finalizing release:
 'development'
[Sentry Webpack Plugin] Creating new release:
 'development'
[Sentry Webpack Plugin] Calling upload-sourcemaps with:
 {
  finalize: true,
  rewrite: true,
  include: [
    {
      paths: [ '/Users/asdf/Projects/test-web/.next/server/pages/' ],
      urlPrefix: '~/_next/server/pages'
    },
    {
      paths: [ '/Users/asdf/Projects/test-web/.next/server/chunks/' ],
      urlPrefix: '~/_next/server/chunks'
    }
  ],
  ignore: [],
  configFile: 'sentry.properties',
  stripPrefix: [ 'webpack://_N_E/' ],
  urlPrefix: '~/_next',
  entries: [Function: entries],
  release: 'development',
  dryRun: true
}
[Sentry Webpack Plugin] Finalizing release:
 'development'
event - compiled client and server successfully in 538 ms (1680 modules)

Expected Result

@sentry/nextjs should be reported to Sentry about API errors.

Actual Result

@sentry/nextjs not reporting errors in next.js api routes

Related Issues

#3917

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Waiting for: Community

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions