v(i)b(e)c(o)d(e)4u.com
Назад на форум vbcd4u.com
🔥 Нейросети2026-11-17T10:09:00.000Z▲ 0 upvotes

Sentry in Next.js App Router: server and client errors, source maps without PII

@murdasoftРедакция vbcd4u · MurdaSoft
Открыть все обсуждения →

What should happen

An error in a server component, Route Handler, Server Action or in the browser goes to Sentry with a readable stack (file names and source lines, not a minified bundle), with a release indication and without personal user data in the event.

Installation

npx @sentry/wizard@latest -i nextjs

The wizard creates files and edits next.config. Figure out what he did, then you support them:

  • instrumentation-client.ts (in older versions of the SDK - sentry.client.config.ts) - initialization in the browser.
  • sentry.server.config.ts and sentry.edge.config.ts - for Node.js and Edge runtime.
  • instrumentation.ts is the entry point that Next.js calls when the server starts.
  • app/global-error.tsx — error limit for the root layout.
// instrumentation.ts
import * as Sentry from "@sentry/nextjs";

export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") await import("./sentry.server.config");
  if (process.env.NEXT_RUNTIME === "edge") await import("./sentry.edge.config");
}

export const onRequestError = Sentry.captureRequestError;

onRequestError is a Next.js 15 hook that is called on rendering errors in Route Handlers and Server Actions. Without this line, server errors often do not reach Sentry: Next.js intercepts them itself and shows the user an error page.

Server configuration without PII

// sentry.server.config.ts
import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  environment: process.env.APP_ENV ?? "production",
  release: process.env.SENTRY_RELEASE,
  sendDefaultPii: false,
  tracesSampleRate: 0.1,
  beforeSend(event) {
    if (event.request) {
      delete event.request.cookies;
      delete event.request.data;
      if (event.request.headers) {
        delete event.request.headers.authorization;
        delete event.request.headers.cookie;
      }
    }
    return event;
  },
});
  • sendDefaultPii: false (this is the default, but explicit is better) - The SDK does not attach the IP address, cookies, and user data headers.
  • beforeSend - last line: removes what could get through integrations or your own context. The body of the request (request.data) is especially dangerous: it contains passwords from the login form and payment data.
  • Specify the user only by identifier: Sentry.setUser({ id: user.id }). The email and name in error events are not needed for debugging, but are stored by a third party.
  • tracesSampleRate: 0.1 - 10% of requests for performance tracing. A value of 1.0 in production will quickly exhaust the quota.

Also check the error texts. `throw new Error(User ${email} not found) отправит адрес в Sentry в сообщении, и никакой sendDefaultPii` will not stop it.

Client and Session Replay

// instrumentation-client.ts
import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  tracesSampleRate: 0.1,
  replaysSessionSampleRate: 0,
  replaysOnErrorSampleRate: 0.2,
  integrations: [Sentry.replayIntegration({ maskAllText: true, blockAllMedia: true })],
});

Replay writes the DOM of the page. maskAllText and blockAllMedia are enabled by default - do not disable them without ensuring that the pages do not contain personal information. Recording only failed sessions (replaysOnErrorSampleRate) provides context for debugging without constantly monitoring users.

The DSN in the browser is public by nature: it only allows you to send events. Limit allowed domains in the Sentry project settings (Allowed Domains) so that other people's sites do not clog your project.

Source maps

// next.config.ts
import { withSentryConfig } from "@sentry/nextjs";

const nextConfig = { /* ... */ };

export default withSentryConfig(nextConfig, {
  org: "my-org",
  project: "web",
  authToken: process.env.SENTRY_AUTH_TOKEN,
  silent: !process.env.CI,
  widenClientFileUpload: true,
  sourcemaps: { deleteSourcemapsAfterUpload: true },
});

During next build the plugin loads source maps into Sentry. deleteSourcemapsAfterUpload removes .map files from the build after uploading so that the source code is not shared with everyone on your site. Check after deployment: a request to any .js.map from /_next/static/chunks/ should return 404.

SENTRY_AUTH_TOKEN is a secret with write permission to the project. It is needed only in CI at the build stage, not in runtime and not in variables with the NEXT_PUBLIC_ prefix.

Diagnostics

  • The stack is minified. Source maps were not loaded or the event release does not coincide with the download release. The sentry-cli sourcemaps explain <event_id> command explains why a particular event was not symbolized.
  • Server errors do not come. There is no onRequestError in instrumentation.ts, or the file is not in the project root (if there is src/ - inside src/).
  • Browser errors do not occur for some users. Ad blockers cut requests to Sentry. The tunnelRoute: "/monitoring" option in withSentryConfig will proxy events through your domain. If the site has a strict CSP, add the receiving domain to connect-src.
  • Nothing arrives at all. Temporarily enable debug: true in Sentry.init and look at the server logs and browser console.

Noise and quotas

Not every mistake is worth the event. Filter out the expected ones: canceled requests, browser extension errors, 404 from bots. Use ignoreErrors for known messages and denyUrls for extension scripts. A project where there are a thousand identical unimportant errors every day teaches the team not to look at Sentry at all.

When Sentry is redundant

For a small internal service, structured logs with the error level and an alert for their number may be enough. Sentry pays off when there is client-side JavaScript, a lot of users and you need to group errors and see which release brought them.

Обсуждение (0)

Ещё на vbcd4u.com