-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
feat(react): add comprehensive getting-started guide with StepConnector #14745
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
336 changes: 336 additions & 0 deletions
336
docs/platforms/javascript/guides/react/getting-started.mdx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,336 @@ | ||
--- | ||
title: "Getting Started" | ||
sidebar_order: 1 | ||
description: "Learn how to get started with the extended functionality of the React SDK and Sentry." | ||
--- | ||
|
||
<PlatformContent includePath="llm-rules-platform" /> | ||
|
||
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. | ||
|
||
<PlatformContent includePath="getting-started-prerequisites" /> | ||
|
||
<StepConnector> | ||
|
||
## Install | ||
|
||
Run the command for your preferred package manager to add the Sentry SDK to your application: | ||
|
||
```bash {tabTitle:npm} | ||
npm install @sentry/react --save | ||
``` | ||
|
||
### Add Readable Stack Traces With Source Maps (Optional) | ||
|
||
<PlatformContent includePath="getting-started-sourcemaps-short-version" /> | ||
|
||
## Configure | ||
|
||
### Initialize the Sentry SDK | ||
|
||
To import and initialize Sentry, create a file in your project's root directory, for example, `instrument.js`, and add the following code: | ||
|
||
```javascript {filename:instrument.js} | ||
import * as Sentry from "@sentry/react"; | ||
|
||
Sentry.init({ | ||
dsn: "___PUBLIC_DSN___", | ||
|
||
// Adds request headers and IP for users, for more info visit: | ||
// https://docs.sentry.io/platforms/javascript/guides/react/configuration/options/#sendDefaultPii | ||
sendDefaultPii: true, | ||
|
||
integrations: [ | ||
// ___PRODUCT_OPTION_START___ performance | ||
Sentry.browserTracingIntegration(), | ||
// ___PRODUCT_OPTION_END___ performance | ||
// ___PRODUCT_OPTION_START___ session-replay | ||
Sentry.replayIntegration(), | ||
// ___PRODUCT_OPTION_END___ session-replay | ||
// ___PRODUCT_OPTION_START___ user-feedback | ||
Sentry.feedbackIntegration({ | ||
// Additional SDK configuration goes in here, for example: | ||
colorScheme: "system", | ||
}), | ||
// ___PRODUCT_OPTION_END___ user-feedback | ||
// ___PRODUCT_OPTION_START___ logs | ||
Sentry.consoleLoggingIntegration({ levels: ["log", "warn", "error"] }), | ||
// ___PRODUCT_OPTION_END___ logs | ||
], | ||
|
||
// ___PRODUCT_OPTION_START___ logs | ||
// For help logging, see: https://docs.sentry.io/platforms/javascript/guides/react/logging/ | ||
enableLogs: true, | ||
// ___PRODUCT_OPTION_END___ logs | ||
|
||
// ___PRODUCT_OPTION_START___ performance | ||
// Set sample rate for performance monitoring | ||
// We recommend adjusting this value in production | ||
tracesSampleRate: 1.0, | ||
// ___PRODUCT_OPTION_END___ performance | ||
|
||
// ___PRODUCT_OPTION_START___ session-replay | ||
// For session replay | ||
// See: https://docs.sentry.io/platforms/javascript/session-replay/ | ||
replaysSessionSampleRate: 0.1, // Sample 10% of sessions | ||
replaysOnErrorSampleRate: 1.0, // Sample 100% of sessions with an error | ||
// ___PRODUCT_OPTION_END___ session-replay | ||
|
||
// ___PRODUCT_OPTION_START___ logs | ||
// For help logging, see: https://docs.sentry.io/platforms/javascript/guides/react/logging/ | ||
extraErrorDataIntegration: false, | ||
// ___PRODUCT_OPTION_END___ logs | ||
}); | ||
``` | ||
|
||
### Import & Use the Instrument file | ||
|
||
Import the `instrument.js` file in your application's entry point _before all other imports_ to initialize the SDK: | ||
|
||
```javascript {filename:index.jsx} {1} | ||
import "./instrument.js"; | ||
import { StrictMode } from "react"; | ||
import { createRoot } from "react-dom/client"; | ||
import App from "./App"; | ||
|
||
const container = document.getElementById("root"); | ||
const root = createRoot(container); | ||
root.render(<App />); | ||
``` | ||
|
||
## Capture React Errors | ||
|
||
To make sure Sentry captures all your app's errors, configure error handling based on your React version. | ||
|
||
### React 19+ | ||
|
||
Starting with React 19, use the `onCaughtError` and `onUncaughtError` root options to capture React errors: | ||
|
||
```javascript {9-15} {filename:index.jsx} | ||
import "./instrument.js"; | ||
import * as Sentry from "@sentry/react"; | ||
import { createRoot } from "react-dom/client"; | ||
import App from "./App"; | ||
|
||
const container = document.getElementById("root"); | ||
const root = createRoot(container, { | ||
// Callback for errors caught by React error boundaries | ||
onCaughtError: Sentry.reactErrorHandler((error, errorInfo) => { | ||
console.error("Caught error:", error, errorInfo.componentStack); | ||
}), | ||
// Callback for errors not caught by React error boundaries | ||
onUncaughtError: Sentry.reactErrorHandler(), | ||
}); | ||
root.render(<App />); | ||
``` | ||
|
||
<Expandable title="React 16–18"> | ||
|
||
### React 16 - 18 | ||
|
||
Use the Sentry Error Boundary to wrap your application: | ||
|
||
```javascript {filename:index.jsx} | ||
import React from "react"; | ||
import * as Sentry from "@sentry/react"; | ||
|
||
<Sentry.ErrorBoundary fallback={<p>An error has occurred</p>} showDialog> | ||
<App /> | ||
</Sentry.ErrorBoundary>; | ||
``` | ||
|
||
<Alert> | ||
Alternatively, if you're using a class component, you can wrap your application | ||
with `Sentry.withErrorBoundary`. Find out more | ||
[here](features/error-boundary/#manually-capturing-errors). | ||
</Alert> | ||
|
||
</Expandable> | ||
|
||
## Sending Logs | ||
|
||
[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. | ||
|
||
Use Sentry's logger to capture structured logs with meaningful attributes that help you debug issues and understand user behavior. | ||
|
||
```javascript | ||
import * as Sentry from "@sentry/react"; | ||
|
||
const { logger } = Sentry; | ||
|
||
// Send structured logs with attributes | ||
logger.info("User completed checkout", { | ||
userId: 123, | ||
orderId: "order_456", | ||
amount: 99.99 | ||
}); | ||
|
||
logger.error("Payment processing failed", { | ||
errorCode: "CARD_DECLINED", | ||
userId: 123, | ||
attemptCount: 3 | ||
}); | ||
|
||
// Using template literals for dynamic data | ||
logger.warn(logger.fmt`Rate limit exceeded for user: ${userId}`); | ||
``` | ||
|
||
## Customizing Replays (Optional) | ||
|
||
[Replays](/product/explore/session-replay/web/getting-started/) allow you to see video-like reproductions of user sessions. | ||
|
||
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. | ||
|
||
```javascript {filename:instrument.js} | ||
import * as Sentry from "@sentry/react"; | ||
|
||
Sentry.init({ | ||
dsn: "___PUBLIC_DSN___", | ||
integrations: [ | ||
Sentry.replayIntegration({ | ||
// This will show the content of the div with the class "reveal-content" and the span with the data-safe-to-show attribute | ||
unmask: [".reveal-content", "[data-safe-to-show]"], | ||
// This will show all text content in replays. Use with caution. | ||
maskAllText: false, | ||
// This will show all media content in replays. Use with caution. | ||
blockAllMedia: false, | ||
}), | ||
], | ||
replaysSessionSampleRate: 0.1, | ||
replaysOnErrorSampleRate: 1.0, | ||
// ... your existing config | ||
}); | ||
``` | ||
|
||
```jsx | ||
<div className="reveal-content">This content will be visible in replays</div> | ||
<span data-safe-to-show>Safe user data: {username}</span> | ||
``` | ||
|
||
## Custom Traces with Attributes (Optional) | ||
|
||
[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. | ||
|
||
```javascript | ||
import * as Sentry from "@sentry/react"; | ||
|
||
// Create custom spans to measure specific operations | ||
async function processUserData(userId) { | ||
return await Sentry.startSpan( | ||
{ | ||
name: "Process User Data", | ||
op: "function", | ||
attributes: { | ||
userId: userId, | ||
operation: "data_processing", | ||
version: "2.1" | ||
} | ||
}, | ||
async () => { | ||
// Your business logic here | ||
const userData = await fetchUserData(userId); | ||
|
||
// Nested span for specific operations | ||
return await Sentry.startSpan( | ||
{ | ||
name: "Transform Data", | ||
op: "transform", | ||
attributes: { | ||
recordCount: userData.length, | ||
transformType: "normalize" | ||
} | ||
}, | ||
() => { | ||
return transformUserData(userData); | ||
} | ||
); | ||
} | ||
); | ||
} | ||
|
||
// Add attributes to existing spans | ||
const span = Sentry.getActiveSpan(); | ||
if (span) { | ||
span.setAttributes({ | ||
cacheHit: true, | ||
region: "us-west-2", | ||
performanceScore: 0.95 | ||
}); | ||
} | ||
``` | ||
|
||
## Avoid Ad Blockers With Tunneling (Optional) | ||
|
||
<PlatformContent includePath="getting-started-tunneling" /> | ||
|
||
## Verify Your Setup | ||
|
||
Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project. | ||
|
||
### Test Error Capturing | ||
|
||
Add the following test button to one of your pages, which will trigger an error that Sentry will capture when you click it: | ||
|
||
```javascript | ||
<button | ||
type="button" | ||
onClick={() => { | ||
throw new Error("Sentry Test Error"); | ||
}} | ||
> | ||
Break the world | ||
</button> | ||
``` | ||
|
||
Open the page in a browser (for most React applications, this will be at localhost) and click the button to trigger a frontend error. | ||
|
||
<PlatformContent includePath="getting-started-browser-sandbox-warning" /> | ||
|
||
### View Captured Data in Sentry | ||
|
||
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). | ||
|
||
<PlatformContent includePath="getting-started-verify-locate-data" /> | ||
|
||
</StepConnector> | ||
|
||
## Next Steps | ||
|
||
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. | ||
|
||
Now's a good time to customize your setup and look into more advanced topics: | ||
|
||
- Extend Sentry to your backend using one of our [SDKs](/) | ||
- Continue to <PlatformLink to="/configuration">customize your configuration</PlatformLink> | ||
- <PlatformLink to="/features/error-boundary">Learn more about the React Error Boundary</PlatformLink> | ||
- Learn how to <PlatformLink to="/usage">manually capture errors</PlatformLink> | ||
- Avoid ad-blockers with <PlatformLink to="/troubleshooting/#using-the-tunnel-option">tunneling</PlatformLink> | ||
|
||
## Additional Resources | ||
|
||
<Expandable title="Set Up React Router (Optional)"> | ||
|
||
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. | ||
|
||
Select your React Router version to start instrumenting your routing: | ||
|
||
- [React Router v7 (library mode)](features/react-router/v7) | ||
- [React Router v6](features/react-router/v6) | ||
- [Older React Router versions](features/react-router) | ||
- [TanStack Router](features/tanstack-router) | ||
|
||
</Expandable> | ||
|
||
<Expandable title="Capture Redux State Data (Optional)"> | ||
|
||
To capture Redux state data, use `Sentry.createReduxEnhancer` when initializing your Redux store. | ||
|
||
<PlatformContent includePath="configuration/redux-init" /> | ||
|
||
</Expandable> | ||
|
||
<Expandable permalink={false} title="Are you having problems setting up the SDK?"> | ||
|
||
- [Get support](https://sentry.zendesk.com/hc/en-us/) | ||
|
||
</Expandable> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bug: Undefined Variable in Template Literal
The
logger.warn
example referencesuserId
within a template literal, butuserId
isn't defined in that scope. This causes aReferenceError
when the code executes.