Demo
General
Observability

Sentry

Learn how to configure and use Sentry for error tracking and performance monitoring.

The starter kit uses Sentry for full-stack error tracking and performance monitoring. Sentry automatically captures errors, exceptions, and performance metrics across your entire application.

Setup

1. Create a Sentry Account

  1. Go to sentry.io and create an account
  2. Create a new project (select Next.js as the platform)
  3. Copy your DSN (Data Source Name)

2. Configure Environment Variables

Add your Sentry credentials to your .env file:

.env
NEXT_PUBLIC_SENTRY_DSN="https://xxxxx@xxxxx.ingest.sentry.io/xxxxx"
SENTRY_ORG="your-org"
SENTRY_PROJECT="your-project"
SENTRY_AUTH_TOKEN="sntrys_xxxxx"

3. Verify Configuration

Sentry is automatically configured in instrumentation.ts, instrumentation-server.ts, instrumentation-edge.ts, and instrumentation-client.ts. The configuration includes:

  • Automatic error capture for client and server
  • Performance monitoring
  • Source map uploads for better error stack traces (configured via sentry.properties and build process)
  • User context tracking

Automatic Instrumentation

Sentry is pre-configured to automatically capture:

Client-Side

  • Unhandled JavaScript exceptions
  • Unhandled promise rejections
  • React component errors (via Error Boundaries)
  • Performance metrics (Core Web Vitals)
  • User session replays (optional)

Server-Side

  • API route errors
  • Server component errors
  • Server action errors
  • tRPC procedure errors (via Sentry tRPC middleware)
  • Database query errors

tRPC Integration

The starter kit uses the Sentry tRPC middleware to automatically capture errors and performance metrics from all tRPC procedures. The middleware is configured in your tRPC setup and automatically:

  • Captures all tRPC procedure errors with full context
  • Tracks procedure execution time and performance
  • Associates errors with the procedure path and input parameters
  • Includes user context when available

The middleware is automatically applied to all procedures, so you don't need to manually instrument your tRPC endpoints.

Manual Error Tracking

Capture Errors

You can manually capture errors in your code:

lib/actions/example.ts
import * as Sentry from '@sentry/nextjs';

try {
  // Your code
} catch (error) {
  Sentry.captureException(error, {
    tags: {
      section: 'billing'
    },
    extra: {
      userId: user.id,
      amount: 100
    }
  });
  throw error;
}

Capture Messages

Log important events:

lib/actions/example.ts
import * as Sentry from '@sentry/nextjs';

Sentry.captureMessage('Payment processed', {
  level: 'info',
  tags: {
    feature: 'billing'
  }
});

Set User Context

Associate errors with users:

lib/auth/session.ts
import * as Sentry from '@sentry/nextjs';

export function setSentryUser(user: { id: string; email: string }) {
  Sentry.setUser({
    id: user.id,
    email: user.email
  });
}

Performance Monitoring

Sentry automatically tracks:

  • Page Load Performance - Time to first byte, first contentful paint
  • API Route Performance - Response times for API routes
  • Database Query Performance - Slow queries are automatically tracked
  • Core Web Vitals - LCP, FID, CLS metrics

Custom Performance Monitoring

Track custom operations using startSpan:

lib/actions/example.ts
import * as Sentry from '@sentry/nextjs';

await Sentry.startSpan(
  {
    name: 'Process Payment',
    op: 'payment'
  },
  async () => {
    // Your payment processing code
    await processPayment();
  }
);

Source Maps

Source maps are automatically uploaded during build to provide readable stack traces in production.

Configuration

Source maps are configured via sentry.properties and the build process. The @sentry/nextjs package automatically:

  1. Generates source maps during build
  2. Uploads them to Sentry (if SENTRY_AUTH_TOKEN, SENTRY_ORG, and SENTRY_PROJECT are set)
  3. Associates them with releases

Releases

Releases help you track which version of your code caused an error. They are automatically configured in the instrumentation files:

instrumentation-server.ts
import { init } from '@sentry/nextjs';

import { env } from '@/lib/env';

init({
  dsn: env.NEXT_PUBLIC_SENTRY_DSN,
  environment: process.env.NODE_ENV
  // Release is automatically set by @sentry/nextjs from Vercel environment variables
});

Session Replay

Session Replay records user sessions to help debug issues. It's already enabled in the client-side instrumentation:

instrumentation-client.ts
import { init, replayIntegration } from '@sentry/nextjs';

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

Filtering Errors

The starter kit already includes comprehensive error filtering in instrumentation-server.ts, instrumentation-edge.ts, and instrumentation-client.ts. You can customize it:

instrumentation-server.ts
import { init } from '@sentry/nextjs';

import { env } from '@/lib/env';

init({
  dsn: env.NEXT_PUBLIC_SENTRY_DSN,
  beforeSend(event) {
    // Filter out specific errors
    const exception = event.exception?.values?.[0];
    if (exception?.value?.includes('ResizeObserver')) {
      return null; // Don't send this error
    }
    return event;
  }
});

Environment-Specific Configuration

Sentry is automatically disabled in development. The configuration in instrumentation-server.ts and instrumentation-edge.ts includes:

  • Automatic disabling in development mode
  • Sample rate of 0.1 (10%) for performance traces
  • Error filtering for common noisy errors (TRPCError NOT_FOUND, ChunkLoadError, network errors, ResizeObserver errors, browser extension errors)

Best Practices

  1. Set appropriate sample rates - Use lower sample rates in production to reduce costs
  2. Filter sensitive data - Don't send passwords, tokens, or PII
  3. Use tags - Add tags to categorize errors (e.g., feature: "billing")
  4. Set user context - Always set user context for better error tracking
  5. Monitor performance - Track slow operations and optimize them
  6. Review errors regularly - Set up alerts for critical errors