Sentry
Learn how to configure and use Sentry for error tracking and performance monitoring.
The starter kit includes a Sentry integration for client, server and edge error
tracking. It remains inactive in development and when
NEXT_PUBLIC_SENTRY_DSN is not configured.
Setup
1. Create a Sentry Account
- Go to sentry.io and create an account
- Create a new project (select Next.js as the platform)
- Copy your DSN (Data Source Name)
2. Configure Environment Variables
Add your Sentry credentials to your .env file:
NEXT_PUBLIC_SENTRY_DSN="https://xxxxx@xxxxx.ingest.sentry.io/xxxxx"
SENTRY_ORG="your-org"
SENTRY_PROJECT="your-project"
SENTRY_AUTH_TOKEN="sntrys_xxxxx"Getting Your Auth Token
Create an auth token in Sentry: Settings →
Auth Tokens → Create New Token. Grant it
project:read and project:releases scopes.
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
- Production source map uploads through
withSentryConfiginnext.config.ts - User and request context for tRPC procedures
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.
Review captured data before production
The shipped tRPC middleware uses attachRpcInput: true and adds
the authenticated user's ID and email to the Sentry scope. Server
instrumentation also sets sendDefaultPii: true. Remove
unnecessary input fields, disable default PII or scrub events in
beforeSend before processing real customer data. Never send
passwords, tokens, payment details or other secrets to Sentry.
Manual Error Tracking
Capture Errors
You can manually capture errors in your code:
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:
import * as Sentry from '@sentry/nextjs';
Sentry.captureMessage('Payment processed', {
level: 'info',
tags: {
feature: 'billing'
}
});Set User Context
Associate errors with users:
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
- Core Web Vitals - LCP, FID, CLS metrics
Custom Performance Monitoring
Track custom operations using startSpan:
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 by withSentryConfig in next.config.ts. During a
production Vercel or CI build, the configuration:
- Generates source maps during build
- Uploads them to Sentry (if
SENTRY_AUTH_TOKEN,SENTRY_ORG, andSENTRY_PROJECTare set) - 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:
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 is already enabled in instrumentation-client.ts when Sentry is
active. The shipped sample rates capture 10% of ordinary sessions and 100% of
sessions containing an error:
import { init, replayIntegration } from '@sentry/nextjs';
init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
integrations: [replayIntegration()],
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0
});Privacy Note Session Replay can capture sensitive data. Review Sentry's masking defaults, add product-specific masking rules and reduce or disable the sample rates if replay is not appropriate for your application.
Filtering Errors
The starter kit already includes error filtering in instrumentation-server.ts and instrumentation-edge.ts. You can customize it:
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)
Best Practices
- Set appropriate sample rates - Use lower sample rates in production to reduce costs
- Filter sensitive data - Don't send passwords, tokens, or PII
- Use tags - Add tags to categorize errors (e.g.,
feature: "billing") - Set user context - Always set user context for better error tracking
- Monitor performance - Track slow operations and optimize them
- Review errors regularly - Set up alerts for critical errors