Skip to main content
Back to Blog
Tutorials
2 min read
November 25, 2024

How to Set Up Error Monitoring with Sentry in Next.js

Integrate Sentry with Next.js for real-time error tracking. Capture server and client errors, source maps, and performance data.

Ryel Banfield

Founder & Lead Developer

Sentry captures errors, exceptions, and performance data from your application in real time. Here is how to set it up with Next.js.

Step 1: Install the Sentry SDK

npx @sentry/wizard@latest -i nextjs

This wizard:

  • Installs @sentry/nextjs
  • Creates configuration files
  • Adds the Sentry webpack plugin for source maps
  • Creates example API route and page for testing

Step 2: Manual Setup (If Not Using Wizard)

pnpm add @sentry/nextjs

Create these configuration files:

sentry.client.config.ts

import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  tracesSampleRate: 1.0,
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
  integrations: [
    Sentry.replayIntegration(),
  ],
});

sentry.server.config.ts

import * as Sentry from "@sentry/nextjs";

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

sentry.edge.config.ts

import * as Sentry from "@sentry/nextjs";

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

Step 3: Configure next.config.ts

import { withSentryConfig } from "@sentry/nextjs";

const nextConfig = {
  // your existing config
};

export default withSentryConfig(nextConfig, {
  org: "your-org",
  project: "your-project",
  silent: !process.env.CI,
  widenClientFileUpload: true,
  tunnelRoute: "/monitoring",
  disableLogger: true,
  automaticVercelMonitors: true,
});

Step 4: Create the Global Error Handler

// app/global-error.tsx
"use client";

import * as Sentry from "@sentry/nextjs";
import { useEffect } from "react";

export default function GlobalError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    Sentry.captureException(error);
  }, [error]);

  return (
    <html>
      <body>
        <div className="flex min-h-screen items-center justify-center">
          <div className="text-center">
            <h2 className="text-2xl font-bold">Something went wrong</h2>
            <button
              onClick={reset}
              className="mt-4 rounded-lg bg-blue-600 px-4 py-2 text-white"
            >
              Try again
            </button>
          </div>
        </div>
      </body>
    </html>
  );
}

Step 5: Create Error Boundaries for Specific Routes

// app/dashboard/error.tsx
"use client";

import * as Sentry from "@sentry/nextjs";
import { useEffect } from "react";

export default function DashboardError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    Sentry.captureException(error);
  }, [error]);

  return (
    <div className="rounded-lg border border-red-200 bg-red-50 p-6">
      <h3 className="font-semibold text-red-800">Dashboard Error</h3>
      <p className="mt-2 text-sm text-red-600">
        Something went wrong loading this section.
      </p>
      <button
        onClick={reset}
        className="mt-4 text-sm font-medium text-red-700 underline"
      >
        Try again
      </button>
    </div>
  );
}

Step 6: Capture Custom Events

import * as Sentry from "@sentry/nextjs";

// Capture a message
Sentry.captureMessage("User completed onboarding", "info");

// Capture with context
Sentry.captureException(error, {
  tags: { feature: "checkout", plan: "professional" },
  extra: { orderId: "12345", amount: 99.99 },
});

// Set user context
Sentry.setUser({
  id: user.id,
  email: user.email,
});

// Add breadcrumbs
Sentry.addBreadcrumb({
  message: "User clicked checkout button",
  category: "ui.click",
  level: "info",
});

Step 7: Monitor Performance

// Wrap API routes
import * as Sentry from "@sentry/nextjs";

export async function GET() {
  return Sentry.withServerActionInstrumentation(
    "fetchProducts",
    async () => {
      const products = await db.query.products.findMany();
      return Response.json(products);
    }
  );
}

Step 8: Environment Variables

# .env.local
NEXT_PUBLIC_SENTRY_DSN=https://abc123@o123456.ingest.sentry.io/123456
SENTRY_AUTH_TOKEN=sntrys_xxx
SENTRY_ORG=your-org
SENTRY_PROJECT=your-project

Step 9: Source Maps

The Sentry Next.js SDK automatically uploads source maps during production builds. Ensure SENTRY_AUTH_TOKEN is set in your CI environment.

# Verify source maps are uploaded
pnpm build

Step 10: Alerts and Notifications

In the Sentry dashboard:

  1. Go to Alerts
  2. Create a new alert rule
  3. Set conditions (e.g., new issue, error spike)
  4. Add notification channels (email, Slack, PagerDuty)

Production Configuration

For production, reduce sample rates:

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  tracesSampleRate: 0.1, // 10% of transactions
  replaysSessionSampleRate: 0.01, // 1% of sessions
  replaysOnErrorSampleRate: 1.0, // 100% of error sessions
  environment: process.env.NODE_ENV,
});

Need Production-Ready Applications?

We build web applications with comprehensive error monitoring, logging, and alerting built in from day one. Contact us to discuss your project.

Sentryerror monitoringNext.jsdebuggingtutorial

Ready to Start Your Project?

RCB Software builds world-class websites and applications for businesses worldwide.

Get in Touch

Related Articles