or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

aws-lambda.mdbrowser-monitoring.mdcustom-attributes.mdcustom-instrumentation.mddistributed-tracing.mderror-handling.mdindex.mdllm-monitoring.mdmetrics-events.mdsegments-timing.mdtransaction-management.mdurl-naming-rules.mdutilities.md
tile.json

tessl/npm-newrelic

Application Performance Monitoring (APM) agent for Node.js applications with transaction tracing, error tracking, custom metrics, and distributed tracing capabilities.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/newrelic@13.2.x

To install, run

npx @tessl/cli install tessl/npm-newrelic@13.2.0

index.mddocs/

New Relic Node.js Agent

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.

Package Information

  • Package Name: newrelic
  • Package Type: npm
  • Language: JavaScript/Node.js
  • Installation: npm install newrelic
  • Minimum Node.js: 20.x
  • License: Apache-2.0

Core Imports

const newrelic = require('newrelic');

For ESM (ES Modules), the agent must be loaded with the import flag:

node --import newrelic/esm-loader.mjs -r newrelic your-app.js

Or preloaded with CommonJS:

node -r newrelic your-app.js

Basic Usage

const newrelic = require('newrelic');

// Custom transaction naming
newrelic.setTransactionName('my-custom-transaction');

// Add custom attributes
newrelic.addCustomAttribute('userId', '12345');
newrelic.addCustomAttribute('planType', 'premium');

// Record custom metrics
newrelic.recordMetric('Custom/MyOperation/Duration', 245);

// Handle errors
try {
  riskyOperation();
} catch (error) {
  newrelic.noticeError(error, { context: 'user-action' });
  throw error;
}

// Custom events for analytics
newrelic.recordCustomEvent('UserAction', {
  action: 'purchase',
  amount: 99.99,
  category: 'electronics'
});

Architecture

The New Relic Agent operates through several key components:

  • Agent Core: Handles initialization, configuration, and communication with New Relic servers
  • Instrumentation System: Automatic and custom instrumentation through shimmer hooks and require patching
  • Transaction Management: Tracks and names web and background transactions with timing data
  • Tracer: Manages execution context and spans for distributed tracing
  • Metric Collection: Gathers performance metrics, custom metrics, and Apdex scores
  • Error Tracking: Captures and reports exceptions with stack traces and custom attributes
  • Event System: Records custom events, log events, and LLM feedback events
  • Browser Monitoring: Generates Real User Monitoring (RUM) scripts for frontend correlation

Capabilities

Transaction Management

Core transaction lifecycle management for web requests and background jobs. Provides manual control over transaction naming, timing, and metadata.

function setTransactionName(name);
function setControllerName(name, action);
function getTransaction();
function startWebTransaction(url, handle);
function startBackgroundTransaction(name, group, handle);
function endTransaction();

Transaction Management

Custom Attributes & Data

Add custom metadata to transactions, spans, and events for enhanced filtering and analysis in New Relic dashboards.

function addCustomAttribute(key, value);
function addCustomAttributes(attributes);
function addCustomSpanAttribute(key, value);
function addCustomSpanAttributes(attributes);
function setUserID(id);

Custom Attributes

Metrics & Events

Record custom metrics and events for business analytics and performance tracking beyond standard APM data.

function recordMetric(name, value);
function incrementMetric(name, value);
function recordCustomEvent(eventType, attributes);
function recordLogEvent(logEvent);

Metrics & Events

Error Handling

Comprehensive error tracking with custom attributes, error grouping, and expected error marking.

function noticeError(error, customAttributes, expected);
function setErrorGroupCallback(callback);

Error Handling

Segments & Timing

Create custom timing segments for specific operations and code blocks within transactions.

function startSegment(name, record, handler, callback);

Segments & Timing

Browser Monitoring

Generate Real User Monitoring (RUM) scripts for correlating server-side performance with client-side metrics.

function getBrowserTimingHeader(options);

Browser Monitoring

Distributed Tracing

Cross-service tracing capabilities with trace metadata extraction and injection for microservices architectures.

function getLinkingMetadata(omitSupportability);
function getTraceMetadata();

Distributed Tracing

Custom Instrumentation

Register custom instrumentation for third-party modules and application-specific code patterns.

function instrument(moduleName, onRequire, onError);
function instrumentDatastore(moduleName, onRequire, onError);
function instrumentWebframework(moduleName, onRequire, onError);
function instrumentMessages(moduleName, onRequire, onError);
function instrumentConglomerate(moduleName, onRequire, onError);
function instrumentLoadedModule(moduleName, module);

Custom Instrumentation

URL Naming Rules

Configure automatic transaction naming patterns and URL filtering for better metric organization.

function addNamingRule(pattern, name);
function addIgnoringRule(pattern);

URL Naming Rules

LLM & AI Monitoring

Specialized monitoring capabilities for Large Language Model applications including token counting and feedback tracking.

function recordLlmFeedbackEvent(params);
function setLlmTokenCountCallback(callback);
function withLlmCustomAttributes(context, callback);

LLM Monitoring

AWS Lambda Support

Serverless monitoring capabilities for AWS Lambda functions with automatic cold start detection.

function setLambdaHandler(handler);

AWS Lambda

Utility Functions

Miscellaneous utility functions for SQL obfuscation, performance tuning, and agent lifecycle management.

function obfuscateSql(sql, dialect);
function ignoreApdex();
function setDispatcher(name, version);
function shutdown(options, callback);

Utilities

Core Types

interface TransactionHandle {
  end(callback?: Function): void;
  ignore(): void;
  isSampled(): boolean;
  acceptDistributedTraceHeaders(transportType: string, headers: object): void;
  insertDistributedTraceHeaders(headers: object): void;
}

interface LinkingMetadata {
  'trace.id': string;
  'span.id': string;
  'entity.name': string;
  'entity.type': string;
  'entity.guid': string;
  hostname: string;
}

interface TraceMetadata {
  traceId: string;
  spanId: string;
}

interface ValidationResult {
  isValid: boolean;
  data: any;
  errors: ValidationError[];
}

interface ValidationError {
  field: string;
  message: string;
  value: any;
}

interface BrowserTimingOptions {
  nonce?: string;
  hasToRemoveScriptWrapper?: boolean;
  allowTransactionlessInjection?: boolean;
}

interface ShutdownOptions {
  collectPendingData?: boolean;
  timeout?: number;
  waitForIdle?: boolean;
}

Automatic Instrumentation

The agent automatically instruments popular Node.js frameworks and libraries including:

  • Web Frameworks: Express, Fastify, Koa, Hapi, NestJS, Connect
  • Databases: MongoDB, PostgreSQL, MySQL, Redis, Cassandra, Prisma
  • Message Queues: RabbitMQ (amqplib), Kafka, AWS SQS/SNS
  • HTTP Clients: Built-in http/https, got, superagent
  • Cloud Services: AWS SDK v2/v3, Google Cloud AI
  • Logging: Winston, Bunyan, Pino
  • Testing: No automatic instrumentation in test environments

Configuration

The agent reads configuration from multiple sources in order of precedence:

  1. Environment variables (NEW_RELIC_LICENSE_KEY, NEW_RELIC_APP_NAME, etc.)
  2. newrelic.js or newrelic.cjs configuration file
  3. Default values
  4. Server-side configuration from New Relic

Key configuration options include high security mode, custom attributes, browser monitoring, distributed tracing, and instrumentation enable/disable flags.