Skip to content

Commit 2a25370

Browse files
committed
Enhance Next.js guide with structured logging and error handling instructions
- Added section on sending structured logs to Sentry. - Updated installation instructions to clarify the use of the installation wizard and manual SDK installation. - Included detailed steps for capturing Next.js errors using app and pages routers. - Expanded on customizing session replays and creating custom traces with attributes. - Added a new section for verifying the setup and included Turbopack support information.
1 parent 3fa6aa0 commit 2a25370

File tree

1 file changed

+176
-13
lines changed
  • docs/platforms/javascript/guides/nextjs

1 file changed

+176
-13
lines changed

docs/platforms/javascript/guides/nextjs/index.mdx

Lines changed: 176 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,31 +17,45 @@ categories:
1717

1818
In addition to capturing errors, you can monitor interactions between multiple services or applications by [enabling tracing](/concepts/key-terms/tracing/). You can also get to the root of an error or performance issue faster, by watching a video-like reproduction of a user session with [session replay](/product/explore/session-replay/web/getting-started/).
1919

20-
Select which Sentry features you'd like to install in addition to Error Monitoring to get the corresponding installation and configuration instructions below.
20+
Send <PlatformLink to="/platforms/javascript/guides/nextjs/logs/">structured logs</PlatformLink> to Sentry and correlate them with errors and traces.
21+
22+
Select which Sentry features you'd like to configure to get the corresponding setup instructions below.
2123

2224
<OnboardingOptionButtons
2325
options={[
24-
"error-monitoring",
25-
"performance",
26-
"session-replay",
27-
"user-feedback",
28-
"logs",
26+
{id: "error-monitoring", checked: true},
27+
{id: "performance", checked: true},
28+
{id: "session-replay", checked: true},
29+
{id: "user-feedback", checked: false},
30+
{id: "logs", checked: true},
2931
]}
3032
/>
3133

3234
## Step 1: Install
3335

34-
To install Sentry using the installation wizard, run the following command within your project:
36+
Run the command for your preferred path to add Sentry to your application.
37+
38+
### Use the Installation Wizard (Recommended)
3539

3640
```bash
3741
npx @sentry/wizard@latest -i nextjs
3842
```
3943

40-
The wizard then guides you through the setup process, asking you to enable additional (optional) Sentry features for your application beyond error monitoring.
44+
The wizard guides you through setup and can enable optional features beyond error monitoring. This guide assumes that you enable all features and allow the wizard to create an example page and route. You can add or remove features at any time.
4145

42-
<PlatformContent includePath="getting-started-features-expandable" />
46+
### Or install the SDK manually
4347

44-
This guide assumes that you enable all features and allow the wizard to create an example page and route. You can add or remove features at any time, but setting them up now will save you the effort of configuring them manually later.
48+
```bash {tabTitle:npm}
49+
npm install @sentry/nextjs --save
50+
```
51+
52+
```bash {tabTitle:yarn}
53+
yarn add @sentry/nextjs
54+
```
55+
56+
```bash {tabTitle:pnpm}
57+
pnpm add @sentry/nextjs
58+
```
4559

4660
<Expandable title="What does the installation wizard change inside your application?">
4761

@@ -56,7 +70,7 @@ This guide assumes that you enable all features and allow the wizard to create a
5670

5771
## Step 2: Configure
5872

59-
If you prefer to configure Sentry manually, here are the configuration files the wizard would create:
73+
If you prefer to configure Sentry manually, here are the configuration files the wizard would create. Initialize Sentry as early as possible.
6074

6175
### Client-Side Configuration
6276

@@ -140,9 +154,152 @@ Sentry.init({
140154

141155
For detailed manual setup instructions, see our [manual setup guide](/platforms/javascript/guides/nextjs/manual-setup/).
142156

143-
## Step 3: Verify Your Setup
157+
## Step 3: Capture Next.js Errors
144158

145-
<Include name="nextjs-turbopack-warning-expandable.mdx" />
159+
Make sure runtime errors are surfaced to Sentry using Next.js error components.
160+
161+
<Expandable title="App Router (app/)">
162+
163+
Create `app/global-error.(tsx|jsx)` to catch uncaught errors:
164+
165+
```tsx {filename:app/global-error.tsx}
166+
"use client";
167+
168+
export default function GlobalError({ error }: { error: Error }) {
169+
return (
170+
<html>
171+
<body>
172+
<h2>Something went wrong!</h2>
173+
<p>{error.message}</p>
174+
<button onClick={() => window.location.reload()}>Try again</button>
175+
</body>
176+
</html>
177+
);
178+
}
179+
```
180+
181+
</Expandable>
182+
183+
<Expandable title="Pages Router (pages/)">
184+
185+
Add `_error.(js|tsx)` to capture render errors:
186+
187+
```tsx {filename:pages/_error.tsx}
188+
import NextErrorComponent from "next/error";
189+
190+
export default NextErrorComponent;
191+
```
192+
193+
</Expandable>
194+
195+
<Alert level="info">
196+
The installation wizard will scaffold these files for you if they are missing.
197+
</Alert>
198+
199+
<OnboardingOption optionId="performance">
200+
201+
<OnboardingOption optionId="logs">
202+
203+
## Step 4: Sending Logs
204+
205+
Now let's add structured logging to capture application insights. Logs are enabled in your configuration above.
206+
207+
Use Sentry's logger to capture structured logs with meaningful attributes that help you debug issues and understand user behavior.
208+
209+
```javascript
210+
import * as Sentry from "@sentry/nextjs";
211+
212+
const { logger } = Sentry;
213+
214+
logger.info("User completed checkout", {
215+
userId: 123,
216+
orderId: "order_456",
217+
amount: 99.99,
218+
});
219+
220+
logger.error("Payment processing failed", {
221+
errorCode: "CARD_DECLINED",
222+
userId: 123,
223+
attemptCount: 3,
224+
});
225+
226+
logger.warn(logger.fmt`Rate limit exceeded for user: ${123}`);
227+
```
228+
229+
</OnboardingOption>
230+
231+
<OnboardingOption optionId="session-replay">
232+
233+
## Step 5: Customizing Replays
234+
235+
By default, Session Replay masks sensitive data for privacy. Customize this to show specific content that's safe to display by adjusting the client-side integration.
236+
237+
```javascript {filename:instrumentation-client.(js|ts)}
238+
import * as Sentry from "@sentry/nextjs";
239+
240+
Sentry.init({
241+
dsn: "___PUBLIC_DSN___",
242+
integrations: [
243+
Sentry.replayIntegration({
244+
unmask: [".reveal-content", "[data-safe-to-show]"],
245+
maskAllText: false,
246+
blockAllMedia: false,
247+
}),
248+
],
249+
replaysSessionSampleRate: 0.1,
250+
replaysOnErrorSampleRate: 1.0,
251+
});
252+
```
253+
254+
```jsx
255+
<div className="reveal-content">This content will be visible in replays</div>
256+
<span data-safe-to-show>Safe user data</span>
257+
```
258+
259+
</OnboardingOption>
260+
261+
## Step 6: Custom Traces with Attributes
262+
263+
Create custom spans to measure specific operations and add meaningful attributes. This helps you understand performance bottlenecks and debug issues with detailed context.
264+
265+
```javascript
266+
import * as Sentry from "@sentry/nextjs";
267+
268+
async function processUserData(userId) {
269+
return await Sentry.startSpan(
270+
{
271+
name: "Process User Data",
272+
op: "function",
273+
attributes: {
274+
userId: userId,
275+
operation: "data_processing",
276+
version: "2.1",
277+
},
278+
},
279+
async () => {
280+
const userData = await fetch(`/api/user?id=${userId}`).then((r) => r.json());
281+
282+
return await Sentry.startSpan(
283+
{
284+
name: "Transform Data",
285+
op: "transform",
286+
attributes: { recordCount: userData.length, transformType: "normalize" },
287+
},
288+
() => transformUserData(userData)
289+
);
290+
}
291+
);
292+
}
293+
294+
const span = Sentry.getActiveSpan();
295+
if (span) {
296+
span.setAttributes({ cacheHit: true, region: "us-west-2", performanceScore: 0.95 });
297+
}
298+
```
299+
300+
</OnboardingOption>
301+
302+
## Step 7: Verify Your Setup
146303

147304
If you haven't tested your Sentry configuration yet, let's do it now. You can confirm that Sentry is working properly and sending data to your Sentry project by using the example page and route created by the installation wizard:
148305

@@ -168,6 +325,10 @@ Now, head over to your project on [Sentry.io](https://sentry.io) to view the col
168325

169326
<PlatformContent includePath="getting-started-verify-locate-data" />
170327

328+
## Turbopack Support
329+
330+
<Include name="nextjs-turbopack-warning-expandable.mdx" />
331+
171332
## Next Steps
172333

173334
At this point, you should have integrated Sentry into your Next.js application and should already be sending error and performance data to your Sentry project.
@@ -181,6 +342,8 @@ Our next recommended steps for you are:
181342
- Get familiar with [Sentry's product features](/product) like tracing, insights, and alerts
182343
- Learn more about our [Vercel integration](/organization/integrations/deployment/vercel/)
183344

345+
<PlatformContent includePath="getting-started-features-expandable" />
346+
184347
<Expandable permalink={false} title="Are you having problems setting up the SDK?">
185348

186349
- If you encountered issues with our installation wizard, try [setting up Sentry manually](/platforms/javascript/guides/nextjs/manual-setup/)

0 commit comments

Comments
 (0)