How to Set Up Error Monitoring with Sentry in 10 Minutes
Running code in production without telemetry is like driving in the dark without headlights. Relying on customer reports to discover bugs means you are already losing users and conversions to system crashes. Automated error monitoring tools like Sentry solve this by catching unhandled exceptions, runtime crashes, and API failures in real time.
Sentry traces failures directly to the line of code that caused them, providing stack traces, breadcrumbs of user interactions, and environmental data. This guide shows how to integrate Sentry into a React application, configure source map uploads, and manage React error boundaries in less than ten minutes.
How Exception Tracking Works
Error monitoring SDKs hook into global browser events to intercept exceptions before they crash the page. The core mechanism involves listening to two primary browser event handlers:
window.onerror: Fired when an uncaught runtime error occurs within scripts.window.onunhandledrejection: Triggered when an asynchronous Promise rejection is not caught by acatch()block.
Sentry wraps these APIs along with console log functions to record the exact path of user actions (clicks, keypresses, fetch requests) leading up to the error, packaging this context and dispatching it to Sentry's ingest servers via non-blocking beacon requests.
Step 1: Installing and Initializing the SDK
To add Sentry to your project, install the React-specific client package using your package manager:
npm install @sentry/react
Initialize the SDK at the entry point of your application (usually index.js or main.tsx) before rendering the React tree. You will need the Data Source Name (DSN) provided in your Sentry project settings:
import * as Sentry from "@sentry/react";
Sentry.init({
dsn: "https://your-dsn-key@o0.ingest.sentry.io/project-id",
integrations: [
Sentry.browserTracingIntegration(),
Sentry.replayIntegration(),
],
// Performance Monitoring
tracesSampleRate: 0.1, // Capture 10% of transactions for performance metrics
// Session Replay
replaysSessionSampleRate: 0.1, // Record 10% of sessions for visual debugging
replaysOnErrorSampleRate: 1.0, // Record 100% of sessions that result in an error
});
Step 2: Configuring Source Map Uploads
To hide source code from users and optimize bundle size, production builds minify and mangle JavaScript assets. When an error is caught in production, the stack trace points to minified lines (e.g., main.js:1:3489), which makes debugging impossible.
Uploading source maps during the build phase maps these cryptic numbers back to your original source files. Sentry provides a Vite plugin to automate this in your CI pipeline:
npm install --save-dev @sentry/vite-plugin
Add the plugin to your vite.config.js configuration file:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { sentryVitePlugin } from "@sentry/vite-plugin";
export default defineConfig({
plugins: [
react(),
sentryVitePlugin({
org: "my-organization",
project: "my-react-project",
authToken: process.env.SENTRY_AUTH_TOKEN,
}),
],
build: {
sourcemap: true, // Tell Vite to output source maps
},
});
Step 3: React Error Boundaries and SDK Telemetry
If an unhandled error occurs during React's rendering lifecycle, React will unmount the entire component tree, leaving the user with a blank white screen. To prevent this, wrap your application components in React Error Boundaries. Sentry provides a wrapper component that intercepts rendering crashes, logs the details, and displays a user-friendly fallback UI:
import * as Sentry from "@sentry/react";
function FallbackComponent({ error, resetErrorBoundary }) {
return (
<div role="alert" style={{ padding: '20px', textAlign: 'center' }}>
<h2>Something went wrong.</h2>
<p>{error.message}</p>
<button onClick={resetErrorBoundary}>Try Again</button>
</div>
);
}
function App() {
return (
<Sentry.ErrorBoundary fallback={FallbackComponent}>
<MyApplicationComponents />
</Sentry.ErrorBoundary>
);
}
Beyond capturing runtime exceptions, Sentry collects Breadcrumbs, which are events that occurred immediately before the error took place. Sentry automatically captures console log actions, network requests, DOM click events, and history navigation.
You can also add custom breadcrumbs manually: Sentry.addBreadcrumb({ category: 'auth', message: 'User updated profile', level: 'info' }). This provides invaluable context when investigating why an exception occurred under rare application states.
Step 4: Release Tracking and Deployment Integration
To fully utilize error tracking, Sentry must associate error logs with specific code commits. This is done through Release Tracking.
By providing a release identifier during Sentry initialization (usually matching your Git commit SHA), Sentry can tell you which release introduced a new bug, and even automatically assign the issue to the developer who committed the code. You can integrate this with your CI pipeline (GitHub Actions) to create a deployment record in Sentry every time code is merged, establishing clear accountability and tracking fix resolutions over time.
Step 5: Privacy, Data Sanitization, and Compliance
When tracking error details from client browsers, you must ensure that sensitive information—such as user passwords, tokens, API keys, or credit card numbers—is never sent to external servers. Sending Personally Identifiable Information (PII) violates privacy regulations like GDPR and CCPA.
Sentry provides a beforeSend hook that intercepts every error payload before it is transmitted. You can implement custom data scrubbing logic in this hook to redact emails or passwords from the stack trace and event context, ensuring your application telemetry remains fully secure and compliant.
Observability and Telemetry at the Edge with Bramsley
Setting up error monitoring is only the first step; analyzing gigabytes of raw telemetry data, configuring complex source-map pipelines, and diagnosing latency spikes without slowing down user interactions requires specialized systems engineering. Bramsley (bramsley.studio) configures and integrates robust, edge-native telemetry systems for enterprise products.
By designing custom logging middleware, configuring Sentry hooks, and tuning telemetry payloads to run asynchronously over edge networks, We ensure client applications maintain total reliability and performance at scale. Partner with us to build an observable and reliable software ecosystem.