Sentry Integration
What is Sentry?
Sentry is an open-source error tracking and performance monitoring platform. It helps developers discover, triage, and prioritize errors in real-time, providing tools to diagnose and fix issues faster.
Key Features
- Error Tracking: Captures uncaught exceptions, handled errors, and performance issues in your application.
- Performance Monitoring: Monitors transaction durations, bottlenecks, and slow performance.
- Contextual Information: Provides rich context data like breadcrumbs, user information, and environment details to reproduce errors.
- Alerting: Notifies you when new issues arise or important error thresholds are crossed.
- Source Maps: Deobfuscates minified JavaScript code to reveal the original, readable source code.
Installation
npm install @sentry/react @sentry/tracing
# or
yarn add @sentry/react @sentry/tracing
Configuration
1. Initialize Sentry
Add this code to the entry point of your application (e.g., index.js
or App.js
). Replace YOUR_DSN
with your actual Sentry DSN.
import * as Sentry from "@sentry/react";
import { BrowserTracing } from "@sentry/tracing";
Sentry.init({
dsn: "YOUR_DSN", // Replace with your Sentry DSN
integrations: [new BrowserTracing()],
// Set tracesSampleRate to 1.0 to capture 100%
// of transactions for performance monitoring.
// We recommend adjusting this value in production
tracesSampleRate: 0.1, // Adjust sampling rate as needed. A lower rate reduces cost.
release: process.env.REACT_APP_VERSION, // Optional: Set the release version. Helpful for correlating errors with specific deploys. Can be a build variable.
environment: process.env.NODE_ENV, // Optional: Set the environment (e.g., "development", "production").
});
Explanation:
dsn
: Data Source Name. This is a unique URL provided by Sentry that tells your application where to send error data.integrations
: Specifies which integrations to use.BrowserTracing
enables performance monitoring.tracesSampleRate
: Determines what percentage of transactions (e.g., page loads, route changes) are sampled for performance monitoring. A value of1.0
captures all transactions, while0.0
captures none. Adjust in production to balance accuracy and data volume.release
: Set automatically during your build process to help track versions and correlates releases and errors, especially with source maps. Access it from env vars.environment
: Specify if the app is running in "development" or "production", which are common values.
2. Configure Route Change Tracking (React Router Example - Optional)
If you're using React Router, you can automatically track route changes as transactions.
import { useLocation } from "react-router-dom";
import { useEffect } from "react";
import * as Sentry from "@sentry/react";
function RouteChangeTracker() {
const location = useLocation();
useEffect(() => {
Sentry.addBreadcrumb({
category: "navigation",
data: {
from: window.location.pathname,
to: location.pathname,
},
message: `Navigated to ${location.pathname}`,
});
Sentry.setContext("route", {
path: location.pathname,
// Can add more route related data here
});
}, [location]);
return null; // This component doesn't render anything.
}
export default RouteChangeTracker;
Insert the RouteChangeTracker
component into your App.js
:
import RouteChangeTracker from "./RouteChangeTracker"; // Adjust import path
import { BrowserRouter } from "react-router-dom"; // Ensure BrowserRouter is used
function App() {
return (
<BrowserRouter>
<RouteChangeTracker />
{/* Your application content */}
</BrowserRouter>
);
}
export default App;
3. Capture Exceptions Manually
Use Sentry.captureException
to manually capture errors that you handle.
try {
// Some risky code
throw new Error("Something went wrong!");
} catch (error) {
Sentry.captureException(error);
}
4. Capture Messages
Use Sentry.captureMessage
to log informative messages, warnings or debug information.
Sentry.captureMessage("User clicked the 'Submit' button", "info"); // levels: 'info', 'warning', 'error', 'fatal', 'debug'
5. Use withErrorBoundary
(React Component Wrapper)
Use the withErrorBoundary
higher order component to gracefully catch errors in your components and report them to Sentry. This prevents entire parts of your UI from crashing.
import * as Sentry from "@sentry/react";
function MyComponent() {
// ... component logic that might throw an error
}
export default Sentry.withErrorBoundary(MyComponent, {
fallback: <p>An error occurred in this component.</p>, // Optional: UI to render when an error occurs
showReportDialog: true, // Optional: Show a dialog asking the user to report the error. Good for getting feedback!
});
Source Maps
- Generate Source Maps: Configure your build process (e.g., Webpack, Parcel) to generate source maps.
- Upload Source Maps to Sentry: Use the Sentry CLI or their build plugins to upload the generated source maps to your Sentry project before deploying your application.
Replace
# Example using the Sentry CLI
sentry-cli releases files "your-release-version" upload-sourcemaps --dist build/static/js build/static/css"your-release-version"
with the release version configured inSentry.init()
.
Best Practices
- Set a Release Version: Always configure the
release
inSentry.init()
. This is critical for correlating errors with specific deployments and for using source maps. - Filter Sensitive Data: Use
beforeSend
to remove or mask any sensitive data (e.g., passwords, API keys) from captured error reports. - Minimize Bundle Size: Use tree-shaking to only include the Sentry code that you actually use.
- Configure Sampling: Adjust
tracesSampleRate
and error sampling to balance accuracy and cost. - Test Thoroughly: Test your Sentry integration in a staging environment before deploying to production.
- Use Breadcrumbs: Add breadcrumbs to provide a timeline of user actions leading up to an error. This adds valuable context to your error reports.
Common Issues
Refused to load the script ... because it violates the following Content Security Policy directive:
: You might need to adjust your Content Security Policy (CSP) to allow Sentry's scripts to load. Addhttps://browser.sentry-cdn.com
to yourscript-src
CSP directive.- Source maps not working: Double-check that your source maps are generated correctly, uploaded to Sentry before deployment, and that the release version matches. Ensure your web server is not actively serving your sourcemaps to public users if they contain sensitive data.
- Errors not showing up in Sentry: Verify that your DSN is correct, your application is reachable by Sentry, and that errors are actually being thrown in your code. Also check the browser console for any Sentry-related errors. Inspect the network tab to make sure events are being sent to the Sentry ingest endpoint.