Sentry for Next.js: Error Tracking That Catches What Logs Miss
Server logs tell you an error occurred. Sentry tells you which user, what browser, the full stack trace, and every breadcrumb leading up to it.
Setup
npx @sentry/wizard@latest -i nextjs
# Automatically configures sentry.client.config.ts, sentry.server.config.ts
Manual Configuration
// sentry.client.config.ts
import * as Sentry from '@sentry/nextjs';
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
tracesSampleRate: 0.1, // 10% of requests traced
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0, // 100% of sessions with errors
integrations: [
Sentry.replayIntegration(),
],
});
// sentry.server.config.ts
import * as Sentry from '@sentry/nextjs';
Sentry.init({
dsn: process.env.SENTRY_DSN,
tracesSampleRate: 0.1,
});
Capturing Errors
import * as Sentry from '@sentry/nextjs';
// Automatic — any uncaught error is captured
// Manual — capture with context
try {
await processPayment(order);
} catch (error) {
Sentry.captureException(error, {
tags: { feature: 'checkout', plan: user.plan },
user: { id: user.id, email: user.email },
extra: { orderId: order.id, amount: order.total },
});
throw error;
}
User Context
// Set once after login — included in all subsequent errors
Sentry.setUser({
id: session.user.id,
email: session.user.email,
username: session.user.name,
});
// Clear on logout
Sentry.setUser(null);
Performance Monitoring
// Create custom spans for slow operations
const transaction = Sentry.startTransaction({ name: 'process-report' });
const fetchSpan = transaction.startChild({ op: 'db.query', description: 'fetch data' });
const data = await fetchReportData();
fetchSpan.finish();
const renderSpan = transaction.startChild({ op: 'render', description: 'generate PDF' });
await generatePDF(data);
renderSpan.finish();
transaction.finish();
Error Boundary (React)
import * as Sentry from '@sentry/nextjs';
export default function GlobalError({ error }: { error: Error }) {
useEffect(() => {
Sentry.captureException(error);
}, [error]);
return (
<html>
<body>
<h2>Something went wrong</h2>
<button onClick={() => window.location.reload()}>Try again</button>
</body>
</html>
);
}
Source Maps
// next.config.ts
import { withSentryConfig } from '@sentry/nextjs';
export default withSentryConfig(nextConfig, {
org: 'your-org',
project: 'your-project',
silent: true,
widenClientFileUpload: true,
hideSourceMaps: true, // Don't expose source maps in browser
});
Sentry ships pre-configured in the AI SaaS Starter Kit — client + server config, user context, error boundaries. $99 at whoffagents.com.
Top comments (0)