Why Production Observability Matters for Next.js Applications
Next.js 15 applications deployed to Vercel, Cloudflare, or self-hosted infrastructure inevitably encounter runtime errors, slow database queries, failing API calls, and edge cases that only appear under real traffic. Without structured observability, debugging relies on logs that lack context, stack traces that point to minified code, and customer complaints that arrive hours later.
Sentry 8 addresses these problems by providing automatic error capture, full stack traces with source maps, distributed tracing for both server and client code, performance metrics, and release tracking. The SDK instruments fetch calls, database drivers, React error boundaries, and Server Actions with minimal manual work. For startups and small teams this means faster incident resolution and fewer production surprises.
The SDK 8 release brings improved support for the App Router, better React Server Component instrumentation, lower overhead tracing, and tighter integration with OpenTelemetry semantic conventions. This guide uses Sentry SDK version 8.7.0 and Next.js 15.0.3. All commands and configuration examples are tested against these exact versions.
Initial Project Setup
Start with a fresh Next.js 15 application using the App Router. Run the following commands:
npx create-next-app@15.0.3 my-sentry-app --typescript --tailwind --eslint --app --yes
cd my-sentry-app
npm install @sentry/nextjs@8.7.0
Instead of manual configuration, use the official Sentry wizard. It modifies next.config.js, creates the required configuration files, and sets up environment variables:
npx @sentry/wizard@latest -i nextjs
The wizard asks for your Sentry organization slug and project name, then adds a new SENTRY_AUTH_TOKEN to your .env.local file. It also creates three configuration files:
sentry.client.config.ts– client-side React instrumentationsentry.server.config.ts– server-side Node.js instrumentationsentry.edge.config.ts– edge runtime instrumentation
After the wizard finishes, your next.config.js will contain the withSentryConfig wrapper. The default configuration already enables source map upload during next build.
Understanding the Generated Configuration Files
The client configuration initializes the React SDK and sets up error boundaries automatically:
import * as Sentry from '@sentry/nextjs';
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
tracesSampleRate: 0.2,
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
integrations: [
Sentry.replayIntegration({
maskAllText: true,
blockAllMedia: true,
}),
],
});
The server configuration uses the Node SDK and automatically instruments fetch, Prisma, Drizzle, and popular ORMs:
import * as Sentry from '@sentry/nextjs';
Sentry.init({
dsn: process.env.SENTRY_DSN,
tracesSampleRate: 0.2,
environment: process.env.NODE_ENV,
});
For edge runtime routes you must import the edge config at the top of each file that uses export const runtime = 'edge'. The wizard also adds a sentry.properties file used during build-time source map upload.
Trade-off: The default tracesSampleRate of 1.0 is too high for production. We will adjust this later based on traffic volume and budget.
Automatic Error Capture in App Router Routes
Server Components, Route Handlers, and Server Actions are automatically instrumented. Throw an error in a Server Component to see it captured:
// app/dashboard/page.tsx
export default async function Dashboard() {
const data = await fetchCriticalData(); // throws in some cases
return <div>...</div>;
}
async function fetchCriticalData() {
const res = await fetch('https://api.example.com/critical', {
cache: 'no-store'
});
if (!res.ok) {
throw new Error(`API error: ${res.status}`);
}
return res.json();
}
Sentry captures the full stack trace, request context, headers (without sensitive values), and the exact line that failed. Because Next.js 15 uses React 19, error boundaries in client components also report hydration mismatches and client-side exceptions automatically.
For Route Handlers you can capture errors manually while still benefiting from automatic transaction creation:
import { captureException } from '@sentry/nextjs';
export async function GET(request: Request) {
try {
// business logic
return Response.json({ success: true });
} catch (error) {
captureException(error, {
tags: { endpoint: 'analytics' },
extra: { userId: request.headers.get('x-user-id') }
});
return new Response('Internal Server Error', { status: 500 });
}
}
Adding Custom Instrumentation and Spans
Automatic instrumentation covers most cases, but complex business logic requires manual spans. Use the startSpan API to create nested transactions:
import { startSpan, setTag } from '@sentry/nextjs';
export async function processOrder(orderId: string, userId: string) {
return startSpan({
name: 'order.process',
op: 'queue.process',
attributes: { 'order.id': orderId }
}, async (span) => {
setTag('user.id', userId);
const validationSpan = await startSpan({ name: 'order.validate' }, async () => {
return validateOrder(orderId);
});
const paymentSpan = await startSpan({ name: 'payment.charge' }, async () => {
return chargeCustomer(orderId);
});
const fulfillmentSpan = await startSpan({ name: 'fulfillment.create' }, async () => {
return createShippingLabel(orderId);
});
return { success: true };
});
}
These spans appear nested in the Sentry trace view, showing exact duration of validation, payment, and fulfillment steps. You can also attach custom measurements:
Sentry.setMeasurement('items_in_cart', 7, 'none');
Sentry.setMeasurement('cart_value_cents', 12450, 'none');
Performance Monitoring and Distributed Tracing
Sentry creates a trace context on incoming requests and propagates it through fetch calls automatically. When your Next.js backend calls a microservice that also has the Sentry SDK, traces connect end-to-end.
Configure sampling rates carefully. A production recommendation for most SaaS products is:
tracesSampler: (samplingContext) => {
const { name, op } = samplingContext;
// Sample health checks at 5%
if (name?.includes('/health')) return 0.05;
// Sample background jobs at 30%
if (op === 'queue.process') return 0.3;
// Sample everything else at 15%
return 0.15;
}
This balances cost and visibility. At 15% sampling with 100,000 daily transactions, you ingest approximately 15,000 traces per day. Sentry's billing is based on ingested transactions, so deliberate sampling is required for cost control.
Connect traces to your database by wrapping Drizzle or Prisma calls. For Drizzle:
const result = await startSpan({
name: 'db.query.orders',
op: 'db.sql',
attributes: { 'db.statement': 'SELECT * FROM orders WHERE user_id = ?' }
}, async () => {
return db.query.orders.findMany({ where: eq(orders.userId, userId) });
});
Configuring Alerts and Issue Workflows
In the Sentry dashboard create two alert rules that cover most production incidents:
- Error Frequency Alert: Trigger when error rate for any issue exceeds 5 occurrences in 10 minutes. Route to Slack #alerts and email on-call engineer.
- High Latency Alert: Trigger when p95 response time for the
/api/checkouttransaction exceeds 1800ms for 5 minutes.
Use Sentry's "Issue Owners" feature by adding code owners files at .github/CODEOWNERS. Sentry automatically assigns frontend errors to the frontend team and checkout errors to the billing team.
For business metric monitoring, send custom events from critical flows:
import { captureMessage } from '@sentry/nextjs';
if (churnedUsers > 12) {
captureMessage('Elevated churn detected', 'warning', {
extra: { count: churnedUsers, period: '24h' }
});
}
Source Maps, Releases, and Deployment Integration
During next build, Sentry automatically uploads source maps when SENTRY_AUTH_TOKEN is present. The wizard already configured this in next.config.js:
const { withSentryConfig } = require('@sentry/nextjs');
module.exports = withSentryConfig(nextConfig, {
silent: true,
org: 'your-org',
project: 'nextjs-frontend',
widenClientFileUpload: true,
tunnelRoute: '/monitoring-tunnel',
});
The tunnelRoute option avoids ad blockers that block connections to *.sentry.io. All events are first sent to your own domain and then forwarded, improving delivery rates.
Create releases tied to git SHAs. In your CI pipeline after successful deployment run:
npx sentry-cli releases new $GIT_SHA
npx sentry-cli releases set-commits $GIT_SHA --auto
npx sentry-cli releases finalize $GIT_SHA
This links errors to the exact commit that introduced them. Sentry can automatically resolve issues when the offending commit reaches production.
Sanitizing Sensitive Data with beforeSend
Never send PII or authentication tokens to Sentry. Use the beforeSend and beforeSendTransaction hooks:
Sentry.init({
dsn: process.env.SENTRY_DSN,
beforeSend(event) {
if (event.request?.headers) {
delete event.request.headers['authorization'];
delete event.request.headers['cookie'];
}
if (event.extra?.email) {
event.extra.email = '[REDACTED]';
}
return event;
},
beforeSendTransaction(transaction) {
// Remove query string parameters that contain tokens
if (transaction.request?.url?.includes('?token=')) {
transaction.request.url = transaction.request.url.split('?')[0];
}
return transaction;
}
});
For applications handling health data or financial information, also enable PII scrubbing rules inside the Sentry project settings using regex patterns.
Monitoring AI and LLM Features
Next.js applications using LLMs benefit from custom instrumentation around inference calls. Track token usage, latency, and error rates per model:
async function generateCompletion(prompt: string, model: string = 'gpt-4o-mini') {
return startSpan({
name: `llm.completion.${model}`,
op: 'llm.completion',
attributes: { 'ai.model': model, 'ai.prompt_tokens': 0 }
}, async (span) => {
const start = Date.now();
try {
const completion = await openai.chat.completions.create({
model,
messages: [{ role: 'user', content: prompt }]
});
const duration = Date.now() - start;
span.setAttribute('ai.completion_tokens', completion.usage?.completion_tokens || 0);
span.setAttribute('ai.total_tokens', completion.usage?.total_tokens || 0);
span.setAttribute('ai.latency_ms', duration);
return completion;
} catch (err) {
span.setStatus({ code: 2 }); // error
throw err;
}
});
}
Create a dashboard in Sentry showing average latency and error rate per model. Set alerts when error rate for OpenAI calls exceeds 3% or when average latency for Llama 3.1 via Ollama exceeds 4500ms.
Sampling Strategies and Cost Control
Sentry charges based on the number of events and transactions ingested. A realistic production budget for a mid-sized SaaS product looks like this:
- Errors: unlimited on most plans, but use
beforeSendto drop low-severity noise - Transactions: target 200,000–800,000 per month depending on plan tier
- Replays: keep session sample rate at 5–10% and error replay rate at 100%
Use dynamic sampling rules in Sentry to prioritize traces from high-value endpoints such as checkout and login. Lower the sample rate for health checks and static asset requests to 1%.
Self-Hosted Sentry vs Cloud
For teams with strict data residency requirements, Sentry can be self-hosted using the official Docker Compose repository. Minimum viable setup requires 4 CPU cores, 8 GB RAM, and persistent volumes for PostgreSQL, ClickHouse, and Redis. Expect 2–3 hours of weekly maintenance for updates and backups.
Cloud Sentry removes operational burden and provides features like Discover queries, AI suggested grouping, and automatic performance regression detection. Most small businesses and startups choose the cloud tier starting at $26/month for the Team plan, which includes 50k errors and 250k transactions.
Troubleshooting Common Integration Issues
Duplicate errors appearing twice: This occurs when both React error boundaries and global handlers report the same exception. Set attachStacktrace: false on the client config or deduplicate using fingerprint rules in Sentry.
Source maps not uploading on Vercel: Ensure the build command includes NEXT_PUBLIC_SENTRY_DSN and that the Sentry auth token is added as an environment variable in the Vercel dashboard with the Production scope.
High memory usage on edge runtimes: The edge SDK is intentionally lightweight. Avoid importing large libraries in edge config files. Use dynamic imports for any heavy instrumentation.
Transactions missing context on Server Actions: Always call Sentry.setContext or Sentry.setUser inside the action before any async work begins. Server Actions run in isolated scopes that do not automatically inherit parent transaction context.
Measuring Impact and Continuous Improvement
After two weeks of stable Sentry usage, review the "Health" tab for each release. Look at crash-free sessions (target > 99.5%), error regression rate, and time to resolution. Use the "Suspect Commits" feature to identify which recent PR introduced a spike in errors.
Create a weekly observability review process: examine the top 10 slowest transactions, the most frequent errors, and any new performance regressions. Tag issues with team names and product areas to enable accurate filtering.
The combination of automatic instrumentation, custom spans for business logic, careful sampling, and integrated alerting gives development teams the confidence to ship frequently while maintaining production stability. Sentry 8 and Next.js 15 work particularly well together because both embrace the React Server Components and edge runtime paradigms.
Implement the configuration shown above, start with a 15% trace sample rate, add custom spans to your most important flows, and set up the two core alerts. Within one deployment cycle you will have visibility that previously required complex custom logging solutions.
The full example repository containing all code snippets, a sample checkout flow, LLM instrumentation, and CI deployment scripts is available at github.com/ajendra/sentry-nextjs-15-example. Clone it, run npm install, add your DSN, and observe errors and traces appearing in your Sentry project within minutes.