Skip to content

Commit cc44b6e

Browse files
authored
Pure JS Next.js example (#1280)
1 parent 440e007 commit cc44b6e

File tree

10 files changed

+651
-0
lines changed

10 files changed

+651
-0
lines changed

examples/next/.gitignore

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
.next
2+
out
3+
build
4+
.DS_Store
5+
.env.local
6+
.nvmrc
7+
CLAUDE*.md

examples/next/README.md

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
# Rollbar Next.js Example
2+
3+
This example demonstrates how to integrate Rollbar error monitoring into a Next.js application using JavaScript.
4+
5+
## Features
6+
7+
- ✅ Next.js with JavaScript (no TypeScript)
8+
- ✅ Rollbar error tracking integration using `@rollbar/react`
9+
- ✅ Error Boundary for catching component errors
10+
- ✅ Manual error reporting
11+
- ✅ Uncaught error tracking
12+
- ✅ Promise rejection handling
13+
- ✅ Custom message logging
14+
- ✅ Server-side rendering (SSR) compatible
15+
16+
## Setup
17+
18+
1. **Install dependencies:**
19+
```bash
20+
npm install
21+
```
22+
23+
Note: Use npm (not yarn) to ensure the local Rollbar package symlink works correctly.
24+
25+
2. **Configure Rollbar:**
26+
- Open `pages/index.js`
27+
- Replace `'YOUR_CLIENT_ACCESS_TOKEN'` with your actual Rollbar project access token
28+
- You can get your access token from your Rollbar project settings
29+
30+
3. **Run the development server:**
31+
```bash
32+
npm run dev
33+
```
34+
35+
The app will start on http://localhost:3001
36+
37+
## Usage
38+
39+
The example provides several interactive buttons to demonstrate Rollbar features:
40+
41+
### 1. **Trigger Manual Error**
42+
Shows how to catch and manually report errors to Rollbar using `rollbar.error()`.
43+
44+
### 2. **Trigger Uncaught Error**
45+
Demonstrates how Rollbar automatically captures uncaught runtime errors.
46+
47+
### 3. **Trigger Promise Rejection**
48+
Shows automatic capture of unhandled promise rejections.
49+
50+
### 4. **Toggle Component Error**
51+
Demonstrates how the Error Boundary catches React component errors and reports them to Rollbar.
52+
53+
### 5. **Log Custom Message**
54+
Shows how to log custom messages and events using `rollbar.info()` and `rollbar.log()`.
55+
56+
## Key Integration Points
57+
58+
### Provider Setup
59+
The app wraps the main component with Rollbar's Provider and ErrorBoundary:
60+
61+
```javascript
62+
<Provider instance={rollbar}>
63+
<ErrorBoundary>
64+
<YourApp />
65+
</ErrorBoundary>
66+
</Provider>
67+
```
68+
69+
### Using the Rollbar Hook
70+
Components can access the Rollbar instance using the `useRollbar` hook:
71+
72+
```javascript
73+
const rollbar = useRollbar();
74+
rollbar.error('Something went wrong', error);
75+
```
76+
77+
### Configuration Options
78+
Common configuration options demonstrated:
79+
- `accessToken`: Your Rollbar project token
80+
- `environment`: Environment name (development, production, etc.)
81+
- `captureUncaught`: Automatically capture uncaught errors
82+
- `captureUnhandledRejections`: Automatically capture promise rejections
83+
- `payload`: Additional data sent with every error (user info, version, etc.)
84+
85+
## Server-Side Considerations
86+
87+
For production deployments with server-side rendering:
88+
89+
1. Initialize Rollbar differently on the server
90+
2. Use environment variables for sensitive configuration
91+
3. Consider implementing custom error pages (`pages/_error.js`)
92+
4. Add source map support for better debugging
93+
94+
## Building for Production
95+
96+
```bash
97+
npm run build
98+
npm run start
99+
```
100+
101+
This creates an optimized production build and starts the production server on port 3001.
102+
103+
## Project Structure
104+
105+
```
106+
├── pages/
107+
│ ├── index.js # Main page with Rollbar integration
108+
│ └── posts/
109+
│ └── first-post.js # Example additional page
110+
├── styles/
111+
│ ├── Home.module.css # Component styles
112+
│ └── global.css # Global styles
113+
├── public/ # Static assets
114+
└── package.json # Dependencies and scripts
115+
```
116+
117+
## Learn More
118+
119+
- [Rollbar Documentation](https://docs.rollbar.com/)
120+
- [Rollbar React SDK](https://docs.rollbar.com/docs/react)
121+
- [Next.js Documentation](https://nextjs.org/docs)
122+
- [Next.js Error Handling](https://nextjs.org/docs/basic-features/error-handling)

examples/next/next.config.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
const path = require("path");
2+
3+
module.exports = {
4+
webpack(config, { isServer }) {
5+
config.devtool = "source-map";
6+
config.optimization.minimize = false;
7+
return config;
8+
},
9+
};

examples/next/package.json

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{
2+
"private": true,
3+
"scripts": {
4+
"build": "next build",
5+
"dev": "next dev -p 3001",
6+
"start": "next start -p 3001"
7+
},
8+
"dependencies": {
9+
"@rollbar/react": "^1.0.0",
10+
"next": "latest",
11+
"prop-types": "^15.8.1",
12+
"react": "18.2.0",
13+
"react-dom": "18.2.0",
14+
"rollbar": "../rollbar.tgz"
15+
},
16+
"engines": {
17+
"node": ">=18"
18+
}
19+
}

examples/next/pages/index.js

Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
1+
import Link from "next/link";
2+
import Head from "next/head";
3+
import styles from "../styles/Home.module.css";
4+
import { useState } from "react";
5+
import { Provider, ErrorBoundary, useRollbar } from "@rollbar/react";
6+
import Rollbar from "rollbar";
7+
8+
// Rollbar configuration
9+
const rollbarConfig = {
10+
accessToken: 'YOUR_CLIENT_ACCESS_TOKEN', // Replace with your actual token
11+
environment: 'development',
12+
captureUncaught: true,
13+
captureUnhandledRejections: true,
14+
payload: {
15+
client: {
16+
javascript: {
17+
source_map_enabled: true,
18+
code_version: '1.0.0',
19+
}
20+
},
21+
person: {
22+
id: 'user123',
23+
24+
username: 'testuser',
25+
}
26+
}
27+
};
28+
29+
// Create Rollbar instance
30+
const rollbar = new Rollbar(rollbarConfig);
31+
32+
// Component that might throw an error
33+
function ErrorProneComponent({ shouldError }) {
34+
if (shouldError) {
35+
throw new Error('React component error for Rollbar testing');
36+
}
37+
return <p className={styles.successMessage}>Component rendered successfully!</p>;
38+
}
39+
40+
export default function App() {
41+
return (
42+
<Provider instance={rollbar}>
43+
<ErrorBoundary>
44+
<Home />
45+
</ErrorBoundary>
46+
</Provider>
47+
);
48+
}
49+
50+
function Home() {
51+
const rollbar = useRollbar();
52+
const [showError, setShowError] = useState(false);
53+
54+
// Function to trigger a manually reported error
55+
const triggerManualError = () => {
56+
try {
57+
throw new Error('Manually triggered error for Rollbar testing');
58+
} catch (error) {
59+
rollbar.error('Manual error caught and reported', error);
60+
alert('Error reported to Rollbar!');
61+
}
62+
};
63+
64+
// Function to trigger an uncaught error
65+
const triggerUncaughtError = () => {
66+
const nullObject = null;
67+
nullObject.nonExistentMethod();
68+
};
69+
70+
// Function to trigger a promise rejection
71+
const triggerPromiseRejection = () => {
72+
new Promise((_, reject) => {
73+
reject(new Error('Promise rejection for Rollbar testing'));
74+
});
75+
alert('Promise rejection triggered!');
76+
};
77+
78+
// Function to log custom messages
79+
const logCustomMessage = () => {
80+
rollbar.info('Custom info message from Next.js app');
81+
rollbar.log('User clicked the custom message button', {
82+
timestamp: new Date().toISOString(),
83+
action: 'button_click',
84+
page: 'home',
85+
});
86+
alert('Custom message logged to Rollbar!');
87+
};
88+
89+
return (
90+
<div className={styles.container}>
91+
<Head>
92+
<title>Rollbar Next.js Example</title>
93+
<link rel="icon" href="/favicon.ico" />
94+
</Head>
95+
96+
<main>
97+
<h1 className={styles.title}>
98+
Rollbar + <Link href="https://nextjs.org">Next.js</Link> Example
99+
</h1>
100+
101+
<p className={styles.description}>
102+
Demonstrate error tracking with Rollbar in Next.js
103+
</p>
104+
105+
<div className={styles.errorButtons}>
106+
<h2>Error Testing</h2>
107+
<div className={styles.buttonGrid}>
108+
<button onClick={triggerManualError} className={styles.errorButton}>
109+
Trigger Manual Error
110+
</button>
111+
<button onClick={triggerUncaughtError} className={`${styles.errorButton} ${styles.danger}`}>
112+
Trigger Uncaught Error
113+
</button>
114+
<button onClick={triggerPromiseRejection} className={styles.errorButton}>
115+
Trigger Promise Rejection
116+
</button>
117+
<button onClick={() => setShowError(!showError)} className={styles.errorButton}>
118+
Toggle Component Error
119+
</button>
120+
<button onClick={logCustomMessage} className={`${styles.errorButton} ${styles.info}`}>
121+
Log Custom Message
122+
</button>
123+
</div>
124+
</div>
125+
126+
<div className={styles.status}>
127+
<ErrorProneComponent shouldError={showError} />
128+
</div>
129+
130+
<div className={styles.instructions}>
131+
<h3>Setup Instructions:</h3>
132+
<ol>
133+
<li>Replace 'YOUR_CLIENT_ACCESS_TOKEN' with your Rollbar project token</li>
134+
<li>Run <code>npm install</code> to install dependencies</li>
135+
<li>Run <code>npm run dev</code> to start the development server</li>
136+
<li>Click the buttons to trigger different types of errors</li>
137+
<li>Check your Rollbar dashboard to see the reported errors</li>
138+
</ol>
139+
</div>
140+
141+
<div className={styles.grid}>
142+
<a href="https://nextjs.org/docs" className={styles.card}>
143+
<h3>Documentation &rarr;</h3>
144+
<p>Find in-depth information about Next.js features and API.</p>
145+
</a>
146+
147+
<a href="https://nextjs.org/learn" className={styles.card}>
148+
<h3>Learn &rarr;</h3>
149+
<p>Learn about Next.js in an interactive course with quizzes!</p>
150+
</a>
151+
152+
<a
153+
href="https://github.com/vercel/next.js/tree/canary/examples"
154+
className={styles.card}
155+
>
156+
<h3>Examples &rarr;</h3>
157+
<p>Discover and deploy boilerplate example Next.js projects.</p>
158+
</a>
159+
160+
<a
161+
href="https://vercel.com/import?filter=next.js&utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
162+
className={styles.card}
163+
>
164+
<h3>Deploy &rarr;</h3>
165+
<p>
166+
Instantly deploy your Next.js site to a public URL with Vercel.
167+
</p>
168+
</a>
169+
</div>
170+
</main>
171+
172+
<footer>
173+
<a
174+
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
175+
target="_blank"
176+
rel="noopener noreferrer"
177+
>
178+
Powered by{" "}
179+
<img src="/vercel.svg" alt="Vercel" className={styles.logo} />
180+
</a>
181+
</footer>
182+
183+
<style jsx>{`
184+
main {
185+
padding: 5rem 0;
186+
flex: 1;
187+
display: flex;
188+
flex-direction: column;
189+
justify-content: center;
190+
align-items: center;
191+
}
192+
footer {
193+
width: 100%;
194+
height: 100px;
195+
border-top: 1px solid #eaeaea;
196+
display: flex;
197+
justify-content: center;
198+
align-items: center;
199+
}
200+
footer img {
201+
margin-left: 0.5rem;
202+
}
203+
footer a {
204+
display: flex;
205+
justify-content: center;
206+
align-items: center;
207+
text-decoration: none;
208+
color: inherit;
209+
}
210+
code {
211+
background: #fafafa;
212+
border-radius: 5px;
213+
padding: 0.75rem;
214+
font-size: 1.1rem;
215+
font-family: Menlo, Monaco, Lucida Console, Liberation Mono,
216+
DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace;
217+
}
218+
`}</style>
219+
220+
<style jsx global>{`
221+
html,
222+
body {
223+
padding: 0;
224+
margin: 0;
225+
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
226+
Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue,
227+
sans-serif;
228+
}
229+
* {
230+
box-sizing: border-box;
231+
}
232+
`}</style>
233+
</div>
234+
);
235+
}

0 commit comments

Comments
 (0)