Skip to content

Commit e917caf

Browse files
committed
react: add Getting Started page (split from current index content)
1 parent cb2eb36 commit e917caf

File tree

1 file changed

+357
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)