0
# New Relic Node.js Agent
1
2
The New Relic Node.js Agent is a comprehensive Application Performance Monitoring (APM) library that provides deep observability into Node.js applications. It automatically instruments popular frameworks and databases while offering extensive APIs for custom instrumentation, transaction management, error tracking, metrics collection, and distributed tracing.
3
4
## Package Information
5
6
- **Package Name**: newrelic
7
- **Package Type**: npm
8
- **Language**: JavaScript/Node.js
9
- **Installation**: `npm install newrelic`
10
- **Minimum Node.js**: 20.x
11
- **License**: Apache-2.0
12
13
## Core Imports
14
15
```javascript
16
const newrelic = require('newrelic');
17
```
18
19
For ESM (ES Modules), the agent must be loaded with the import flag:
20
```bash
21
node --import newrelic/esm-loader.mjs -r newrelic your-app.js
22
```
23
24
Or preloaded with CommonJS:
25
```bash
26
node -r newrelic your-app.js
27
```
28
29
## Basic Usage
30
31
```javascript
32
const newrelic = require('newrelic');
33
34
// Custom transaction naming
35
newrelic.setTransactionName('my-custom-transaction');
36
37
// Add custom attributes
38
newrelic.addCustomAttribute('userId', '12345');
39
newrelic.addCustomAttribute('planType', 'premium');
40
41
// Record custom metrics
42
newrelic.recordMetric('Custom/MyOperation/Duration', 245);
43
44
// Handle errors
45
try {
46
riskyOperation();
47
} catch (error) {
48
newrelic.noticeError(error, { context: 'user-action' });
49
throw error;
50
}
51
52
// Custom events for analytics
53
newrelic.recordCustomEvent('UserAction', {
54
action: 'purchase',
55
amount: 99.99,
56
category: 'electronics'
57
});
58
```
59
60
## Architecture
61
62
The New Relic Agent operates through several key components:
63
64
- **Agent Core**: Handles initialization, configuration, and communication with New Relic servers
65
- **Instrumentation System**: Automatic and custom instrumentation through shimmer hooks and require patching
66
- **Transaction Management**: Tracks and names web and background transactions with timing data
67
- **Tracer**: Manages execution context and spans for distributed tracing
68
- **Metric Collection**: Gathers performance metrics, custom metrics, and Apdex scores
69
- **Error Tracking**: Captures and reports exceptions with stack traces and custom attributes
70
- **Event System**: Records custom events, log events, and LLM feedback events
71
- **Browser Monitoring**: Generates Real User Monitoring (RUM) scripts for frontend correlation
72
73
## Capabilities
74
75
### Transaction Management
76
77
Core transaction lifecycle management for web requests and background jobs. Provides manual control over transaction naming, timing, and metadata.
78
79
```javascript { .api }
80
function setTransactionName(name);
81
function setControllerName(name, action);
82
function getTransaction();
83
function startWebTransaction(url, handle);
84
function startBackgroundTransaction(name, group, handle);
85
function endTransaction();
86
```
87
88
[Transaction Management](./transaction-management.md)
89
90
### Custom Attributes & Data
91
92
Add custom metadata to transactions, spans, and events for enhanced filtering and analysis in New Relic dashboards.
93
94
```javascript { .api }
95
function addCustomAttribute(key, value);
96
function addCustomAttributes(attributes);
97
function addCustomSpanAttribute(key, value);
98
function addCustomSpanAttributes(attributes);
99
function setUserID(id);
100
```
101
102
[Custom Attributes](./custom-attributes.md)
103
104
### Metrics & Events
105
106
Record custom metrics and events for business analytics and performance tracking beyond standard APM data.
107
108
```javascript { .api }
109
function recordMetric(name, value);
110
function incrementMetric(name, value);
111
function recordCustomEvent(eventType, attributes);
112
function recordLogEvent(logEvent);
113
```
114
115
[Metrics & Events](./metrics-events.md)
116
117
### Error Handling
118
119
Comprehensive error tracking with custom attributes, error grouping, and expected error marking.
120
121
```javascript { .api }
122
function noticeError(error, customAttributes, expected);
123
function setErrorGroupCallback(callback);
124
```
125
126
[Error Handling](./error-handling.md)
127
128
### Segments & Timing
129
130
Create custom timing segments for specific operations and code blocks within transactions.
131
132
```javascript { .api }
133
function startSegment(name, record, handler, callback);
134
```
135
136
[Segments & Timing](./segments-timing.md)
137
138
### Browser Monitoring
139
140
Generate Real User Monitoring (RUM) scripts for correlating server-side performance with client-side metrics.
141
142
```javascript { .api }
143
function getBrowserTimingHeader(options);
144
```
145
146
[Browser Monitoring](./browser-monitoring.md)
147
148
### Distributed Tracing
149
150
Cross-service tracing capabilities with trace metadata extraction and injection for microservices architectures.
151
152
```javascript { .api }
153
function getLinkingMetadata(omitSupportability);
154
function getTraceMetadata();
155
```
156
157
[Distributed Tracing](./distributed-tracing.md)
158
159
### Custom Instrumentation
160
161
Register custom instrumentation for third-party modules and application-specific code patterns.
162
163
```javascript { .api }
164
function instrument(moduleName, onRequire, onError);
165
function instrumentDatastore(moduleName, onRequire, onError);
166
function instrumentWebframework(moduleName, onRequire, onError);
167
function instrumentMessages(moduleName, onRequire, onError);
168
function instrumentConglomerate(moduleName, onRequire, onError);
169
function instrumentLoadedModule(moduleName, module);
170
```
171
172
[Custom Instrumentation](./custom-instrumentation.md)
173
174
### URL Naming Rules
175
176
Configure automatic transaction naming patterns and URL filtering for better metric organization.
177
178
```javascript { .api }
179
function addNamingRule(pattern, name);
180
function addIgnoringRule(pattern);
181
```
182
183
[URL Naming Rules](./url-naming-rules.md)
184
185
### LLM & AI Monitoring
186
187
Specialized monitoring capabilities for Large Language Model applications including token counting and feedback tracking.
188
189
```javascript { .api }
190
function recordLlmFeedbackEvent(params);
191
function setLlmTokenCountCallback(callback);
192
function withLlmCustomAttributes(context, callback);
193
```
194
195
[LLM Monitoring](./llm-monitoring.md)
196
197
### AWS Lambda Support
198
199
Serverless monitoring capabilities for AWS Lambda functions with automatic cold start detection.
200
201
```javascript { .api }
202
function setLambdaHandler(handler);
203
```
204
205
[AWS Lambda](./aws-lambda.md)
206
207
### Utility Functions
208
209
Miscellaneous utility functions for SQL obfuscation, performance tuning, and agent lifecycle management.
210
211
```javascript { .api }
212
function obfuscateSql(sql, dialect);
213
function ignoreApdex();
214
function setDispatcher(name, version);
215
function shutdown(options, callback);
216
```
217
218
[Utilities](./utilities.md)
219
220
## Core Types
221
222
```javascript { .api }
223
interface TransactionHandle {
224
end(callback?: Function): void;
225
ignore(): void;
226
isSampled(): boolean;
227
acceptDistributedTraceHeaders(transportType: string, headers: object): void;
228
insertDistributedTraceHeaders(headers: object): void;
229
}
230
231
interface LinkingMetadata {
232
'trace.id': string;
233
'span.id': string;
234
'entity.name': string;
235
'entity.type': string;
236
'entity.guid': string;
237
hostname: string;
238
}
239
240
interface TraceMetadata {
241
traceId: string;
242
spanId: string;
243
}
244
245
interface ValidationResult {
246
isValid: boolean;
247
data: any;
248
errors: ValidationError[];
249
}
250
251
interface ValidationError {
252
field: string;
253
message: string;
254
value: any;
255
}
256
257
interface BrowserTimingOptions {
258
nonce?: string;
259
hasToRemoveScriptWrapper?: boolean;
260
allowTransactionlessInjection?: boolean;
261
}
262
263
interface ShutdownOptions {
264
collectPendingData?: boolean;
265
timeout?: number;
266
waitForIdle?: boolean;
267
}
268
```
269
270
## Automatic Instrumentation
271
272
The agent automatically instruments popular Node.js frameworks and libraries including:
273
274
- **Web Frameworks**: Express, Fastify, Koa, Hapi, NestJS, Connect
275
- **Databases**: MongoDB, PostgreSQL, MySQL, Redis, Cassandra, Prisma
276
- **Message Queues**: RabbitMQ (amqplib), Kafka, AWS SQS/SNS
277
- **HTTP Clients**: Built-in http/https, got, superagent
278
- **Cloud Services**: AWS SDK v2/v3, Google Cloud AI
279
- **Logging**: Winston, Bunyan, Pino
280
- **Testing**: No automatic instrumentation in test environments
281
282
## Configuration
283
284
The agent reads configuration from multiple sources in order of precedence:
285
286
1. Environment variables (NEW_RELIC_LICENSE_KEY, NEW_RELIC_APP_NAME, etc.)
287
2. newrelic.js or newrelic.cjs configuration file
288
3. Default values
289
4. Server-side configuration from New Relic
290
291
Key configuration options include high security mode, custom attributes, browser monitoring, distributed tracing, and instrumentation enable/disable flags.