Skip to content

Commit 3c7e549

Browse files
committed
feat(react): add getting-started guide with StepConnector
- Add comprehensive React getting-started guide with step-by-step flow - Fix StepConnector component quote style consistency (single -> double quotes) - Include error monitoring, logging, tracing, and replay configuration - Add React 19+ error handling with onCaughtError/onUncaughtError - Include optional customizations for replays and traces
1 parent e52aeca commit 3c7e549

File tree

2 files changed

+358
-22
lines changed

2 files changed

+358
-22
lines changed
Lines changed: 336 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,336 @@
1+
---
2+
title: "Getting Started"
3+
sidebar_order: 1
4+
description: "Learn how to get started with the extended functionality of the React SDK and Sentry."
5+
---
6+
7+
<PlatformContent includePath="llm-rules-platform" />
8+
9+
This guide covers the full getting started pocess for the React SDK and assumes you want to utilize Error Monitoring, Logs, Tracing and Spans, and Replays. For the basic quickstart, the [React Quickstart](/platforms/javascript/guides/react/) guide is a better starting point.
10+
11+
<PlatformContent includePath="getting-started-prerequisites" />
12+
13+
<StepConnector>
14+
15+
## Install
16+
17+
Run the command for your preferred package manager to add the Sentry SDK to your application:
18+
19+
```bash {tabTitle:npm}
20+
npm install @sentry/react --save
21+
```
22+
23+
### Add Readable Stack Traces With Source Maps (Optional)
24+
25+
<PlatformContent includePath="getting-started-sourcemaps-short-version" />
26+
27+
## Configure
28+
29+
### Initialize the Sentry SDK
30+
31+
To import and initialize Sentry, create a file in your project's root directory, for example, `instrument.js`, and add the following code:
32+
33+
```javascript {filename:instrument.js}
34+
import * as Sentry from "@sentry/react";
35+
36+
Sentry.init({
37+
dsn: "___PUBLIC_DSN___",
38+
39+
// Adds request headers and IP for users, for more info visit:
40+
// https://docs.sentry.io/platforms/javascript/guides/react/configuration/options/#sendDefaultPii
41+
sendDefaultPii: true,
42+
43+
integrations: [
44+
// ___PRODUCT_OPTION_START___ performance
45+
Sentry.browserTracingIntegration(),
46+
// ___PRODUCT_OPTION_END___ performance
47+
// ___PRODUCT_OPTION_START___ session-replay
48+
Sentry.replayIntegration(),
49+
// ___PRODUCT_OPTION_END___ session-replay
50+
// ___PRODUCT_OPTION_START___ user-feedback
51+
Sentry.feedbackIntegration({
52+
// Additional SDK configuration goes in here, for example:
53+
colorScheme: "system",
54+
}),
55+
// ___PRODUCT_OPTION_END___ user-feedback
56+
// ___PRODUCT_OPTION_START___ logs
57+
Sentry.consoleLoggingIntegration({ levels: ["log", "warn", "error"] }),
58+
// ___PRODUCT_OPTION_END___ logs
59+
],
60+
61+
// ___PRODUCT_OPTION_START___ logs
62+
// For help logging, see: https://docs.sentry.io/platforms/javascript/guides/react/logging/
63+
enableLogs: true,
64+
// ___PRODUCT_OPTION_END___ logs
65+
66+
// ___PRODUCT_OPTION_START___ performance
67+
// Set sample rate for performance monitoring
68+
// We recommend adjusting this value in production
69+
tracesSampleRate: 1.0,
70+
// ___PRODUCT_OPTION_END___ performance
71+
72+
// ___PRODUCT_OPTION_START___ session-replay
73+
// For session replay
74+
// See: https://docs.sentry.io/platforms/javascript/session-replay/
75+
replaysSessionSampleRate: 0.1, // Sample 10% of sessions
76+
replaysOnErrorSampleRate: 1.0, // Sample 100% of sessions with an error
77+
// ___PRODUCT_OPTION_END___ session-replay
78+
79+
// ___PRODUCT_OPTION_START___ logs
80+
// For help logging, see: https://docs.sentry.io/platforms/javascript/guides/react/logging/
81+
extraErrorDataIntegration: false,
82+
// ___PRODUCT_OPTION_END___ logs
83+
});
84+
```
85+
86+
### Import & Use the Instrument file
87+
88+
Import the `instrument.js` file in your application's entry point _before all other imports_ to initialize the SDK:
89+
90+
```javascript {filename:index.jsx} {1}
91+
import "./instrument.js";
92+
import { StrictMode } from "react";
93+
import { createRoot } from "react-dom/client";
94+
import App from "./App";
95+
96+
const container = document.getElementById("root");
97+
const root = createRoot(container);
98+
root.render(<App />);
99+
```
100+
101+
## Capture React Errors
102+
103+
To make sure Sentry captures all your app's errors, configure error handling based on your React version.
104+
105+
### React 19+
106+
107+
Starting with React 19, use the `onCaughtError` and `onUncaughtError` root options to capture React errors:
108+
109+
```javascript {9-15} {filename:index.jsx}
110+
import "./instrument.js";
111+
import * as Sentry from "@sentry/react";
112+
import { createRoot } from "react-dom/client";
113+
import App from "./App";
114+
115+
const container = document.getElementById("root");
116+
const root = createRoot(container, {
117+
// Callback for errors caught by React error boundaries
118+
onCaughtError: Sentry.reactErrorHandler((error, errorInfo) => {
119+
console.error("Caught error:", error, errorInfo.componentStack);
120+
}),
121+
// Callback for errors not caught by React error boundaries
122+
onUncaughtError: Sentry.reactErrorHandler(),
123+
});
124+
root.render(<App />);
125+
```
126+
127+
<Expandable title="React 16–18">
128+
129+
### React 16 - 18
130+
131+
Use the Sentry Error Boundary to wrap your application:
132+
133+
```javascript {filename:index.jsx}
134+
import React from "react";
135+
import * as Sentry from "@sentry/react";
136+
137+
<Sentry.ErrorBoundary fallback={<p>An error has occurred</p>} showDialog>
138+
<App />
139+
</Sentry.ErrorBoundary>;
140+
```
141+
142+
<Alert>
143+
Alternatively, if you're using a class component, you can wrap your application
144+
with `Sentry.withErrorBoundary`. Find out more
145+
[here](features/error-boundary/#manually-capturing-errors).
146+
</Alert>
147+
148+
</Expandable>
149+
150+
## Sending Logs
151+
152+
[Structured logging](/platforms/javascript/guides/react/logs/) lets users send text-based log information from their applications to Sentry. Once in Sentry, these logs can be viewed alongside relevant errors, searched by text-string, or searched using their individual attributes.
153+
154+
Use Sentry's logger to capture structured logs with meaningful attributes that help you debug issues and understand user behavior.
155+
156+
```javascript
157+
import * as Sentry from "@sentry/react";
158+
159+
const { logger } = Sentry;
160+
161+
// Send structured logs with attributes
162+
logger.info("User completed checkout", {
163+
userId: 123,
164+
orderId: "order_456",
165+
amount: 99.99
166+
});
167+
168+
logger.error("Payment processing failed", {
169+
errorCode: "CARD_DECLINED",
170+
userId: 123,
171+
attemptCount: 3
172+
});
173+
174+
// Using template literals for dynamic data
175+
logger.warn(logger.fmt`Rate limit exceeded for user: ${userId}`);
176+
```
177+
178+
## Customizing Replays (Optional)
179+
180+
[Replays](/product/explore/session-replay/web/getting-started/) allow you to see video-like reproductions of user sessions.
181+
182+
By default, Session Replay masks sensitive data for privacy and to protect PII data. You can modify the replay configurations in your client-side Sentry initialization to show (unmask) specific content that's safe to display.
183+
184+
```javascript {filename:instrument.js}
185+
import * as Sentry from "@sentry/react";
186+
187+
Sentry.init({
188+
dsn: "___PUBLIC_DSN___",
189+
integrations: [
190+
Sentry.replayIntegration({
191+
// This will show the content of the div with the class "reveal-content" and the span with the data-safe-to-show attribute
192+
unmask: [".reveal-content", "[data-safe-to-show]"],
193+
// This will show all text content in replays. Use with caution.
194+
maskAllText: false,
195+
// This will show all media content in replays. Use with caution.
196+
blockAllMedia: false,
197+
}),
198+
],
199+
replaysSessionSampleRate: 0.1,
200+
replaysOnErrorSampleRate: 1.0,
201+
// ... your existing config
202+
});
203+
```
204+
205+
```jsx
206+
<div className="reveal-content">This content will be visible in replays</div>
207+
<span data-safe-to-show>Safe user data: {username}</span>
208+
```
209+
210+
## Custom Traces with Attributes (Optional)
211+
212+
[Tracing](/platforms/javascript/guides/react/tracing/) allows you to monitor interactions between multiple services or applications. Create custom spans to measure specific operations and add meaningful attributes. This helps you understand performance bottlenecks and debug issues with detailed context.
213+
214+
```javascript
215+
import * as Sentry from "@sentry/react";
216+
217+
// Create custom spans to measure specific operations
218+
async function processUserData(userId) {
219+
return await Sentry.startSpan(
220+
{
221+
name: "Process User Data",
222+
op: "function",
223+
attributes: {
224+
userId: userId,
225+
operation: "data_processing",
226+
version: "2.1"
227+
}
228+
},
229+
async () => {
230+
// Your business logic here
231+
const userData = await fetchUserData(userId);
232+
233+
// Nested span for specific operations
234+
return await Sentry.startSpan(
235+
{
236+
name: "Transform Data",
237+
op: "transform",
238+
attributes: {
239+
recordCount: userData.length,
240+
transformType: "normalize"
241+
}
242+
},
243+
() => {
244+
return transformUserData(userData);
245+
}
246+
);
247+
}
248+
);
249+
}
250+
251+
// Add attributes to existing spans
252+
const span = Sentry.getActiveSpan();
253+
if (span) {
254+
span.setAttributes({
255+
cacheHit: true,
256+
region: "us-west-2",
257+
performanceScore: 0.95
258+
});
259+
}
260+
```
261+
262+
## Avoid Ad Blockers With Tunneling (Optional)
263+
264+
<PlatformContent includePath="getting-started-tunneling" />
265+
266+
## Verify Your Setup
267+
268+
Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project.
269+
270+
### Test Error Capturing
271+
272+
Add the following test button to one of your pages, which will trigger an error that Sentry will capture when you click it:
273+
274+
```javascript
275+
<button
276+
type="button"
277+
onClick={() => {
278+
throw new Error("Sentry Test Error");
279+
}}
280+
>
281+
Break the world
282+
</button>
283+
```
284+
285+
Open the page in a browser (for most React applications, this will be at localhost) and click the button to trigger a frontend error.
286+
287+
<PlatformContent includePath="getting-started-browser-sandbox-warning" />
288+
289+
### View Captured Data in Sentry
290+
291+
Now, head over to your project on [Sentry.io](https://sentry.io/) to view the collected data (it takes a couple of moments for the data to appear).
292+
293+
<PlatformContent includePath="getting-started-verify-locate-data" />
294+
295+
</StepConnector>
296+
297+
## Next Steps
298+
299+
At this point, you should have integrated Sentry into your React application and should already be sending error and performance data to your Sentry project.
300+
301+
Now's a good time to customize your setup and look into more advanced topics:
302+
303+
- Extend Sentry to your backend using one of our [SDKs](/)
304+
- Continue to <PlatformLink to="/configuration">customize your configuration</PlatformLink>
305+
- <PlatformLink to="/features/error-boundary">Learn more about the React Error Boundary</PlatformLink>
306+
- Learn how to <PlatformLink to="/usage">manually capture errors</PlatformLink>
307+
- Avoid ad-blockers with <PlatformLink to="/troubleshooting/#using-the-tunnel-option">tunneling</PlatformLink>
308+
309+
## Additional Resources
310+
311+
<Expandable title="Set Up React Router (Optional)">
312+
313+
If you're using `react-router` in your application, you need to set up the Sentry integration for your specific React Router version to trace `navigation` events.
314+
315+
Select your React Router version to start instrumenting your routing:
316+
317+
- [React Router v7 (library mode)](features/react-router/v7)
318+
- [React Router v6](features/react-router/v6)
319+
- [Older React Router versions](features/react-router)
320+
- [TanStack Router](features/tanstack-router)
321+
322+
</Expandable>
323+
324+
<Expandable title="Capture Redux State Data (Optional)">
325+
326+
To capture Redux state data, use `Sentry.createReduxEnhancer` when initializing your Redux store.
327+
328+
<PlatformContent includePath="configuration/redux-init" />
329+
330+
</Expandable>
331+
332+
<Expandable permalink={false} title="Are you having problems setting up the SDK?">
333+
334+
- [Get support](https://sentry.zendesk.com/hc/en-us/)
335+
336+
</Expandable>

0 commit comments

Comments
 (0)