Skip to content

Commit fc13eeb

Browse files
authored
Typescript Next.js example (#1281)
1 parent cc44b6e commit fc13eeb

File tree

17 files changed

+828
-0
lines changed

17 files changed

+828
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
.next
2+
build
3+
.vercel
4+
*.tsbuildinfo
5+
next-env.d.ts

examples/next-typescript/README.md

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
# Rollbar Next.js TypeScript Example
2+
3+
This example demonstrates how to integrate Rollbar error monitoring into a Next.js application using TypeScript, showcasing type-safe error tracking and reporting.
4+
5+
## Features
6+
7+
- ✅ Next.js with TypeScript configuration
8+
- ✅ Rollbar error tracking with full type support
9+
- ✅ Type-safe Rollbar configuration using `Rollbar.Configuration`
10+
- ✅ Error Boundary with proper TypeScript types
11+
- ✅ Manual error reporting with type checking
12+
- ✅ Uncaught error and promise rejection tracking
13+
- ✅ Custom typed metadata for error context
14+
- ✅ IntelliSense support for all Rollbar methods
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.tsx`
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:3002
36+
37+
## TypeScript Benefits Demonstrated
38+
39+
### 1. **Type-Safe Configuration**
40+
```typescript
41+
const rollbarConfig: Rollbar.Configuration = {
42+
accessToken: 'YOUR_TOKEN',
43+
environment: 'development',
44+
// TypeScript ensures all options are valid
45+
};
46+
```
47+
48+
### 2. **Proper Error Type Checking**
49+
```typescript
50+
try {
51+
throw new Error('Something went wrong');
52+
} catch (error) {
53+
if (error instanceof Error) {
54+
rollbar.error('Error caught', error);
55+
}
56+
}
57+
```
58+
59+
### 3. **Typed Component Props**
60+
```typescript
61+
interface ErrorProneComponentProps {
62+
shouldError: boolean;
63+
}
64+
65+
function ErrorProneComponent({ shouldError }: ErrorProneComponentProps) {
66+
// Component implementation
67+
}
68+
```
69+
70+
### 4. **Custom Typed Metadata**
71+
```typescript
72+
interface ErrorMetadata {
73+
timestamp: string;
74+
action: string;
75+
page?: string;
76+
[key: string]: unknown;
77+
}
78+
79+
const metadata: ErrorMetadata = {
80+
timestamp: new Date().toISOString(),
81+
action: 'button_click',
82+
page: 'home',
83+
};
84+
```
85+
86+
## Interactive Demo Features
87+
88+
The example provides interactive buttons to test different error scenarios:
89+
90+
### 1. **Trigger Manual Error**
91+
- Demonstrates type-safe error catching and reporting
92+
- Uses `instanceof Error` type guard for proper error handling
93+
94+
### 2. **Trigger Uncaught Error**
95+
- Shows how Rollbar captures runtime errors automatically
96+
- TypeScript helps prevent many of these errors at compile time
97+
98+
### 3. **Trigger Promise Rejection**
99+
- Demonstrates typed Promise error handling
100+
- Shows automatic capture of unhandled rejections
101+
102+
### 4. **Toggle Component Error**
103+
- Tests Error Boundary with typed component props
104+
- Shows React component error tracking
105+
106+
### 5. **Log Custom Message**
107+
- Demonstrates logging with typed metadata
108+
- Shows IntelliSense support for Rollbar methods
109+
110+
## Key TypeScript Integration Points
111+
112+
### Type Imports
113+
```typescript
114+
import Rollbar from "rollbar";
115+
// Rollbar.Configuration type is automatically available
116+
```
117+
118+
### React Hooks with Types
119+
```typescript
120+
const rollbar = useRollbar();
121+
// rollbar is properly typed with all available methods
122+
```
123+
124+
### Async Error Handling
125+
```typescript
126+
const fetchData = async (): Promise<void> => {
127+
try {
128+
const response = await fetch('/api/data');
129+
if (!response.ok) {
130+
throw new Error(`HTTP error! status: ${response.status}`);
131+
}
132+
} catch (error) {
133+
rollbar.error('Fetch failed', error as Error);
134+
}
135+
};
136+
```
137+
138+
## Building for Production
139+
140+
```bash
141+
npm run build
142+
npm run start
143+
```
144+
145+
TypeScript compilation is handled automatically during the build process. Any type errors will prevent the build from completing.
146+
147+
## Type Checking
148+
149+
Run TypeScript compiler to check for type errors without building:
150+
151+
```bash
152+
npx tsc --noEmit
153+
```
154+
155+
## Project Structure
156+
157+
```
158+
├── pages/
159+
│ ├── index.tsx # Main page with typed Rollbar integration
160+
│ ├── _app.tsx # Next.js app component
161+
│ └── api/
162+
│ └── hello.ts # Example API route with types
163+
├── styles/
164+
│ ├── Home.module.css # Component styles
165+
│ └── globals.css # Global styles
166+
├── tsconfig.json # TypeScript configuration
167+
├── next.config.ts # Next.js configuration
168+
└── package.json # Dependencies and scripts
169+
```
170+
171+
## Learn More
172+
173+
- [Rollbar Documentation](https://docs.rollbar.com/)
174+
- [Rollbar TypeScript Types](https://github.com/rollbar/rollbar.js/blob/master/index.d.ts)
175+
- [Next.js TypeScript Documentation](https://nextjs.org/docs/basic-features/typescript)
176+
- [TypeScript Documentation](https://www.typescriptlang.org/docs/)
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import type { NextConfig } from "next";
2+
3+
const nextConfig: NextConfig = {
4+
/* config options here */
5+
reactStrictMode: true,
6+
};
7+
8+
export default nextConfig;
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{
2+
"name": "next-typescript",
3+
"version": "0.1.0",
4+
"private": true,
5+
"scripts": {
6+
"dev": "next dev -p 3002",
7+
"build": "next build",
8+
"start": "next start -p 3002",
9+
"lint": "next lint"
10+
},
11+
"dependencies": {
12+
"@rollbar/react": "^1.0.0",
13+
"react": "19.1.0",
14+
"react-dom": "19.1.0",
15+
"next": "15.4.5",
16+
"rollbar": "file::../rollbar.tgz"
17+
},
18+
"devDependencies": {
19+
"typescript": "^5",
20+
"@types/node": "^20",
21+
"@types/react": "^19",
22+
"@types/react-dom": "^19"
23+
},
24+
"engines": {
25+
"node": ">=18"
26+
}
27+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import "@/styles/globals.css";
2+
import type { AppProps } from "next/app";
3+
4+
export default function App({ Component, pageProps }: AppProps) {
5+
return <Component {...pageProps} />;
6+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { Html, Head, Main, NextScript } from "next/document";
2+
3+
export default function Document() {
4+
return (
5+
<Html lang="en">
6+
<Head />
7+
<body>
8+
<Main />
9+
<NextScript />
10+
</body>
11+
</Html>
12+
);
13+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
2+
import type { NextApiRequest, NextApiResponse } from "next";
3+
4+
type Data = {
5+
name: string;
6+
};
7+
8+
export default function handler(
9+
req: NextApiRequest,
10+
res: NextApiResponse<Data>,
11+
) {
12+
res.status(200).json({ name: "John Doe" });
13+
}

0 commit comments

Comments
 (0)