Skip to content

[nextjs] Custom _error page does not capture server data fetching/SSR errors with experimental-serverless-trace target #4168

@JamiesWhiteShirt

Description

@JamiesWhiteShirt

Package + Version

  • @sentry/browser
  • @sentry/node
  • raven-js
  • raven-node (raven for node)
  • other: @sentry/nextjs

Version:

6.16.1

Description

Using [email protected].

Note that this does not happen when running a Next.js development server. To reproduce locally, it has to be built with next build then served with next start. If the first request made to the server has getInitialProps throw an error, the error will not be captured. This is not the recommended way to run serverless Next.js, but it allows us to reproduce an issue that we have on Lambda@Edge with https://github.com/serverless-nextjs/serverless-next.js

In addition to adding Sentry configuration to next.config.js, the documentation suggests creating a custom error page to capture errors from data fetching methods or rendering. When the server encounters such an error when using the experimental-serverless-trace target (as required for serverless environments with Sentry, though no longer recommended by Next.js maintainers), the error capturing logic is called as expected, but the events are not actually reported to Sentry. When browser scripting similarly fails data fetching via getInitialProps or encounters an error during CSR (client side navigation via next/router or next/link), the same error capturing logic captures the error successfully. API errors are also still captured normally. Therefore the problem is specific to non-API pages on the server.

The cause appears to be that the Sentry SDK is not initialized in time, causing it to silently swallow the error. A simple experiment adding a console.log statement before the initialization of the SDK in sentry.server.config.[jt]s and another in the top of _error's getInitialProps function shows that getInitialProps is called before the sentry.server.config.[jt]s module is loaded. Switching from experimental-serverless-trace to the default target changes it to the order you would expect, and report errors as expected.

Reconfiguring Next.js' Webpack entrypoints to include the Sentry initialization logic first is somewhat complex, so I suspect it might be the cause but cannot say for sure. I have little confidence in this as a solution, but a tiny tweak to add Sentry initialization to /pages/_error in shouldAddSentryToEntrypoint seems to cause the Sentry SDK to initialize in time. @lobsterkatie Do you think this could make sense as a solution?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Package: nextjsIssues related to the Sentry Nextjs SDK

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions