0
# Server Integration
1
2
Node.js specific features including Express middleware, AWS Lambda integration, callback wrapping, and local variable capture for enhanced server-side error tracking.
3
4
## Capabilities
5
6
### Express Error Handler
7
8
Creates Express.js middleware for handling errors in Express applications.
9
10
```typescript { .api }
11
/**
12
* Create Express.js error handling middleware
13
* @returns Express error handler middleware function
14
*/
15
function errorHandler(): ExpressErrorHandler;
16
17
type ExpressErrorHandler = (
18
err: any,
19
request: any,
20
response: any,
21
next: ExpressNextFunction
22
) => any;
23
24
interface ExpressNextFunction {
25
(err?: any): void;
26
}
27
```
28
29
**Usage Example:**
30
31
```javascript
32
const express = require('express');
33
const Rollbar = require('rollbar');
34
35
const rollbar = new Rollbar({
36
accessToken: 'YOUR_ACCESS_TOKEN',
37
environment: 'production'
38
});
39
40
const app = express();
41
42
// Your routes
43
app.get('/', (req, res) => {
44
throw new Error('This will be caught by Rollbar');
45
});
46
47
// Use Rollbar error handler (should be last middleware)
48
app.use(rollbar.errorHandler());
49
50
app.listen(3000);
51
```
52
53
### Lambda Handler Wrapper
54
55
Wraps AWS Lambda handlers with error reporting and timeout handling.
56
57
```typescript { .api }
58
/**
59
* Wrap AWS Lambda handler with error reporting
60
* @param handler - Lambda handler function to wrap
61
* @returns Wrapped Lambda handler with error reporting
62
*/
63
function lambdaHandler<T = object>(
64
handler: LambdaHandler<T>
65
): LambdaHandler<T>;
66
67
type LambdaHandler<TEvent = any, TResult = any, TContext = any> = (
68
event: TEvent,
69
context: TContext,
70
callback: Callback<TResult>
71
) => void | Promise<TResult>;
72
```
73
74
**Usage Examples:**
75
76
```javascript
77
const Rollbar = require('rollbar');
78
79
const rollbar = new Rollbar({
80
accessToken: 'YOUR_ACCESS_TOKEN',
81
environment: 'production',
82
captureLambdaTimeouts: true
83
});
84
85
// Wrap callback-style handler
86
exports.handler = rollbar.lambdaHandler((event, context, callback) => {
87
try {
88
const result = processEvent(event);
89
callback(null, result);
90
} catch (error) {
91
callback(error); // Will be reported to Rollbar
92
}
93
});
94
95
// Wrap async handler
96
exports.asyncHandler = rollbar.lambdaHandler(async (event, context) => {
97
// Any uncaught errors will be reported
98
const data = await fetchData(event.id);
99
return processData(data);
100
});
101
```
102
103
### Callback Wrapper
104
105
Wraps callback functions with error handling.
106
107
```typescript { .api }
108
/**
109
* Wrap callback function with error handling
110
* @param callback - Callback function to wrap
111
* @returns Wrapped callback that reports errors to Rollbar
112
*/
113
function wrapCallback(callback: Function): Function;
114
```
115
116
**Usage Example:**
117
118
```javascript
119
const fs = require('fs');
120
121
// Wrap callback to catch and report errors
122
fs.readFile('file.txt', rollbar.wrapCallback((err, data) => {
123
if (err) {
124
// Error will be automatically reported to Rollbar
125
return;
126
}
127
console.log(data.toString());
128
}));
129
```
130
131
### Local Variable Capture
132
133
Capture local variables from stack frames for enhanced debugging (Node.js 10+).
134
135
```typescript { .api }
136
interface LocalsSettings {
137
module: LocalsType;
138
enabled?: boolean;
139
uncaughtOnly?: boolean;
140
depth?: number;
141
maxProperties?: number;
142
maxArray?: number;
143
}
144
145
type LocalsOptions = LocalsType | LocalsSettings;
146
```
147
148
**Configuration Example:**
149
150
```javascript
151
const rollbar = new Rollbar({
152
accessToken: 'YOUR_ACCESS_TOKEN',
153
locals: {
154
enabled: true,
155
uncaughtOnly: false, // Capture for all errors, not just uncaught
156
depth: 3, // Maximum call stack depth to capture
157
maxProperties: 5, // Maximum object properties per frame
158
maxArray: 5 // Maximum array elements per frame
159
}
160
});
161
```
162
163
### Request Data Collection
164
165
Automatically collect and include HTTP request data with error reports.
166
167
```typescript { .api }
168
/**
169
* Custom function to add request data to error reports
170
*/
171
interface AddRequestDataFunction {
172
(data: Dictionary, req: Dictionary): void;
173
}
174
```
175
176
**Configuration Example:**
177
178
```javascript
179
const rollbar = new Rollbar({
180
accessToken: 'YOUR_ACCESS_TOKEN',
181
addRequestData: (data, req) => {
182
// Add custom request data
183
data.custom_request_id = req.headers['x-request-id'];
184
data.user_agent = req.headers['user-agent'];
185
data.ip_address = req.ip;
186
}
187
});
188
```
189
190
### Lambda Timeout Handling
191
192
Automatically capture and report Lambda function timeouts.
193
194
```typescript { .api }
195
captureLambdaTimeouts?: boolean;
196
```
197
198
**Configuration Example:**
199
200
```javascript
201
const rollbar = new Rollbar({
202
accessToken: 'YOUR_ACCESS_TOKEN',
203
captureLambdaTimeouts: true // Enable Lambda timeout capture
204
});
205
```
206
207
### Node.js Source Maps
208
209
Enable source map processing for better stack traces in Node.js.
210
211
```typescript { .api }
212
nodeSourceMaps?: boolean;
213
```
214
215
**Configuration Example:**
216
217
```javascript
218
const rollbar = new Rollbar({
219
accessToken: 'YOUR_ACCESS_TOKEN',
220
nodeSourceMaps: true // Enable source map processing
221
});
222
```
223
224
## Server-Specific Configuration Options
225
226
### Host Configuration
227
228
```typescript { .api }
229
host?: string;
230
```
231
232
The hostname of the server. Defaults to `os.hostname()`.
233
234
### Exit on Uncaught Exception
235
236
```typescript { .api }
237
exitOnUncaughtException?: boolean;
238
```
239
240
Whether to exit the process when an uncaught exception occurs. Default is `true`.
241
242
### Default Scrub Headers
243
244
Server-side includes additional headers that are scrubbed by default:
245
246
```javascript
247
[
248
'authorization', 'www-authorization', 'http_authorization',
249
'omniauth.auth', 'cookie', 'oauth-access-token', 'x-access-token',
250
'x_csrf_token', 'http_x_csrf_token', 'x-csrf-token'
251
]
252
```
253
254
### Server Payload Configuration
255
256
```typescript { .api }
257
interface ServerPayload {
258
server?: {
259
branch?: string;
260
host?: string;
261
root?: string;
262
[property: string]: any;
263
};
264
}
265
```
266
267
## Complete Server Setup Example
268
269
```javascript
270
const express = require('express');
271
const Rollbar = require('rollbar');
272
273
// Initialize Rollbar
274
const rollbar = new Rollbar({
275
accessToken: 'YOUR_POST_SERVER_ITEM_ACCESS_TOKEN',
276
environment: process.env.NODE_ENV || 'development',
277
278
// Error handling
279
captureUncaught: true,
280
captureUnhandledRejections: true,
281
exitOnUncaughtException: true,
282
283
// Reporting levels
284
reportLevel: 'warning',
285
286
// Local variable capture
287
locals: {
288
enabled: true,
289
uncaughtOnly: false,
290
depth: 3
291
},
292
293
// Request data
294
addRequestData: (data, req) => {
295
data.headers = req.headers;
296
data.method = req.method;
297
data.url = req.url;
298
data.query = req.query;
299
data.body = req.body;
300
},
301
302
// Payload customization
303
payload: {
304
server: {
305
host: require('os').hostname(),
306
branch: process.env.GIT_BRANCH || 'main'
307
},
308
environment: process.env.NODE_ENV || 'development'
309
}
310
});
311
312
const app = express();
313
314
// Middleware
315
app.use(express.json());
316
317
// Routes
318
app.get('/', (req, res) => {
319
rollbar.info('Homepage accessed');
320
res.send('Hello World!');
321
});
322
323
app.get('/error', (req, res) => {
324
throw new Error('Test error for Rollbar');
325
});
326
327
// Rollbar error handler (must be last)
328
app.use(rollbar.errorHandler());
329
330
app.listen(3000, () => {
331
rollbar.info('Server started on port 3000');
332
});
333
334
// Graceful shutdown
335
process.on('SIGTERM', () => {
336
rollbar.info('Server shutting down');
337
rollbar.wait(() => {
338
process.exit(0);
339
});
340
});
341
```
342
343
## AWS Lambda Example
344
345
```javascript
346
const Rollbar = require('rollbar');
347
348
const rollbar = new Rollbar({
349
accessToken: 'YOUR_ACCESS_TOKEN',
350
environment: process.env.ENVIRONMENT || 'development',
351
captureLambdaTimeouts: true,
352
captureUncaught: true,
353
captureUnhandledRejections: true
354
});
355
356
// API Gateway handler
357
exports.handler = rollbar.lambdaHandler(async (event, context) => {
358
rollbar.info('Lambda function invoked', {
359
requestId: context.awsRequestId,
360
functionName: context.functionName
361
});
362
363
try {
364
const result = await processRequest(event);
365
366
return {
367
statusCode: 200,
368
body: JSON.stringify(result)
369
};
370
} catch (error) {
371
rollbar.error('Lambda function error', error, {
372
event: event,
373
context: context
374
});
375
376
return {
377
statusCode: 500,
378
body: JSON.stringify({ error: 'Internal Server Error' })
379
};
380
}
381
});
382
383
async function processRequest(event) {
384
// Your business logic here
385
if (Math.random() < 0.1) {
386
throw new Error('Random error for testing');
387
}
388
389
return { message: 'Success', timestamp: new Date().toISOString() };
390
}
391
```