Exception Catching
Guides developers on using Sentry for exception capture, tracing, and logging in a Next.js project.
What this file does
Guides developers on using Sentry for exception capture, tracing, and logging in a Next.js project.
When to use it
- Adding Sentry error tracking to a Next.js app
- Instrumenting custom spans for button clicks and API calls
- Configuring Sentry logging with consoleLoggingIntegration
- Setting up Sentry initialization in client, server, and edge files
Assumes this stack
trigger: manual description: globs:
These examples should be used as guidance when configuring Sentry functionality within a project.
Exception Catching
Use Sentry.captureException(error) to capture an exception and log the error in Sentry.
Use this in try catch blocks or areas where exceptions are expected
Tracing Examples
Spans should be created for meaningful actions within applications like button clicks, API calls, and function calls
Use the Sentry.startSpan function to create a span
Child spans can exist within a parent span
Custom Span instrumentation in component actions
The name and op properties should be meaningful for the activities in the call.
Attach attributes based on relevant information and metrics from the request
function TestComponent() {
const handleTestButtonClick = () => {
// Create a transaction/span to measure performance
Sentry.startSpan(
{
op: "ui.click",
name: "Test Button Click",
},
(span) => {
const value = "some config";
const metric = "some metric";
// Metrics can be added to the span
span.setAttribute("config", value);
span.setAttribute("metric", metric);
doSomething();
},
);
};
return (
<button type="button" onClick={handleTestButtonClick}>
Test Sentry
</button>
);
}
Custom span instrumentation in API calls
The name and op properties should be meaningful for the activities in the call.
Attach attributes based on relevant information and metrics from the request
async function fetchUserData(userId) {
return Sentry.startSpan(
{
op: "http.client",
name: `GET /api/users/${userId}`,
},
async () => {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
return data;
},
);
}
Logs
Where logs are used, ensure Sentry is imported using import * as Sentry from "@sentry/nextjs"
Enable logging in Sentry using Sentry.init({ enableLogs: true })
Reference the logger using Sentry.logger
Sentry offers a consoleLoggingIntegration that can be used to log specific console error types automatically without instrumenting the individual logger calls
Configuration
In NextJS the client side Sentry initialization is in instrumentation-client.ts, the server initialization is in sentry.server.config.ts and the edge initialization is in sentry.edge.config.ts
Initialization does not need to be repeated in other files, it only needs to happen the files mentioned above. You should use import * as Sentry from "@sentry/nextjs" to reference Sentry functionality
Baseline
import * as Sentry from "@sentry/nextjs";
Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
enableLogs: true,
});
Logger Integration
Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
integrations: [
// send console.log, console.error, and console.warn calls as logs to Sentry
Sentry.consoleLoggingIntegration({ levels: ["log", "error", "warn"] }),
],
});
Logger Examples
logger.fmt is a template literal function that should be used to bring variables into the structured logs.
logger.trace("Starting database connection", { database: "users" });
logger.debug(logger.fmt`Cache miss for user: ${userId}`);
logger.info("Updated profile", { profileId: 345 });
logger.warn("Rate limit reached for endpoint", {
endpoint: "/api/results/",
isEnterprise: false,
});
logger.error("Failed to process payment", {
orderId: "order_123",
amount: 99.99,
});
logger.fatal("Database connection pool exhausted", {
database: "users",
activeConnections: 100,
});
What's inside
3 main sections: Exception Catching, Tracing Examples (2 code snippets), Logs (3 subsections, 2 code examples).
Change this for your project
- Replace
"https://examplePublicKey@o0.ingest.sentry.io/0"with your Sentry DSN - Replace
"Test Button Click"and"GET /api/users/${userId}"with your own span names and operations
Where it goes
Save as AGENTS.md in your repository root. Read by Codex, Cursor and other agents that follow the AGENTS.md convention.
Worth borrowing
- Using Sentry.startSpan with meaningful op and name for performance measurement
- Attaching custom attributes to spans for additional context
- Leveraging logger.fmt for structured logging with variables
Related Documents
Browser-only development
Guides AI assistants on an Electron + React + TypeScript desktop app for browsing and organizing AI-generated images locally.
Claude Agents — Reference & Recommendations
Catalogues 40+ Claude agents and marketing skills for building a cat adoption charity landing page, with a ready-to-paste prompt and backend API reference.
Golden DKG Prototype -- Master Plan
Defines an 8-phase implementation plan for a Rust prototype of the Golden non-interactive DKG protocol using BLS12-381 and tokio.
Swarms Examples Index
Lists 60+ example scripts for building single and multi-agent systems with the Swarms framework, organized by category and use case.