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
- 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
- Source map uploads for better error stack traces (configured via
sentry.propertiesand 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:
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
- Database Query Performance - Slow queries are automatically tracked
- 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 via sentry.properties and the build process. The @sentry/nextjs package automatically:
- 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 records user sessions to help debug issues. It's already enabled in the client-side instrumentation:
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
});Privacy Note Session Replay can capture sensitive data. Configure masking rules to protect user privacy.
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:
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
- 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