Skip to content
Learni
View all tutorials
Observabilité

How to Monitor a Node.js App with New Relic in 2026

Lire en français

Introduction

New Relic is the leading observability platform in 2026, providing unified Application Performance Monitoring (APM), infrastructure, and logs in a single interface. For a Node.js app, this means tracing slow requests, detecting memory leaks, and alerting on CPU spikes in real time. This intermediate tutorial guides you step by step: from agent installation to custom dashboards. Why is it crucial? In production, 70% of incidents stem from performance degradation (source: New Relic State of Observability 2025). With these steps, you'll deploy full-stack monitoring in under an hour, scalable for microservices. Think of it like an airplane cockpit dashboard for your code—New Relic displays latency, throughput, and errors without excessive DevOps effort. Ready to turn your logs into actionable insights? (142 words)

Prerequisites

  • Free New Relic account (sign up at one.newrelic.com) with license key from Account Settings > API Keys.
  • Node.js 18+ installed.
  • A basic Node.js app (Express recommended).
  • Shell access for package installation.
  • Intermediate TypeScript/JS knowledge.

Installing the New Relic Agent for Node.js

terminal-install.sh
mkdir my-node-app && cd my-node-app
npm init -y
npm install express newrelic
npm install --save-dev nodemon

This script sets up an empty Node.js project, installs Express for the API and the official New Relic agent. Nodemon is added for hot-reload in development. Tip: Always use --save-dev for dev tools to avoid production bundles; run in an empty directory to prevent package.json conflicts.

First Launch and Getting Your License Key

Log in to one.newrelic.com, go to APM & Services > New apps to see your app appear after instrumentation. Copy your license key (format: NRxx-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX) from Account > API keys > License key. Paste it into the config below. Tip: Enable Instant Observability for a guided UI onboarding that auto-scans your endpoints and creates basic dashboards in 2 clicks.

Full Agent Configuration (newrelic.js)

newrelic.js
    'license_key': 'VOTRE_LICENSE_KEY_ICI',
    'logging': {
      'level': 'info'
    },
    'max_event_samples_stored': 10000,
    'slow_sql': {
      'enabled': true
    },
    'errors_wrapper': ['__express_error_handler'],
    'attributes': {
      'exclude': [
        'request.headers.cookie',
        'request.headers.authorization',
        'request.headers.proxyAuthorization',
        'request.headers.setcookie*',
        'request.headers.x*',
        'response.headers.cookie',
        'response.headers.authorization',
        'response.headers.setcookie*'
      ]
    }
  };

  // Injecte distributed tracing
  if (process.env.NEW_RELIC_DISTRIBUTED_TRACING_ENABLED === 'true') {
    newrelicConfig.distributed_tracing = {
      enabled: true
    };
  }

This config file activates the agent with info-level logging, slow SQL detection, and exclusion of sensitive attributes (PII/GDPR compliance). Distributed tracing is optional via ENV. Pitfall: Replace VOTRE_LICENSE_KEY_ICI with your real key, or the agent will fail silently; place this file at the project root for auto-loading.

Automatic App Instrumentation

The New Relic agent instruments via require('newrelic') on the first line, automatically capturing Express routes, DB queries, and HTTP clients. Test with npm run dev: In the New Relic UI, your app appears under APM > Services with basic metrics (response time, throughput). Filter by Golden signals to prioritize latency and errors.

Instrumented Express Application

app.js
require('newrelic');

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

app.use(express.json());

app.get('/', (req, res) => {
  res.json({ message: 'Hello monitored by New Relic!' });
});

app.get('/slow', async (req, res) => {
  // Simule slow query
  await new Promise(resolve => setTimeout(resolve, 2000));
  res.json({ message: 'Slow endpoint for testing' });
});

app.listen(port, () => {
  console.log(`App listening on port ${port}`);
});

This basic Express app is auto-traced: New Relic captures the '/' and '/slow' endpoints with timings. The artificial delay tests slow SQL detection. Tip: Add NEW_RELIC_APP_NAME=MonAppNode as an ENV var for precise naming; avoid unhandled async/await that can crash silently in production.

Launch and First UI Verification

  • Launch: node app.js or nodemon app.js.
  • Open one.newrelic.com > APM > Services > your app.
  • Check Overview: Apdex score >0.9, error rate <1%. Click Transactions for detailed traces. Analogy: Like a live profiler, it traces stacks per request.

Adding Custom Metrics and Errors

app-custom-metrics.js
require('newrelic');

const express = require('express');
const app = express();

app.use(express.json());

app.post('/user/:id', (req, res) => {
  const userId = req.params.id;
  newrelic.getContextManager().setCustomAttribute('user.id', userId);
  newrelic.recordCustomEvent('UserLogin', {
    userId: userId,
    success: true
  });

  if (Math.random() < 0.1) {
    throw new Error('Simulated user error');
  }

  res.json({ success: true });
});

app.use((err, req, res, next) => {
  newrelic.noticeError(err);
  res.status(500).json({ error: err.message });
});

app.listen(3000, () => console.log('Custom metrics app on 3000'));

Adds custom attributes (user.id), events, and noticeError for errors. This enriches traces in the UI under Events > Custom. Pitfall: Call noticeError only in a global middleware; otherwise, errors are lost. Use for business metrics like 'UserLogin'.

Infrastructure Agent Configuration (YAML)

newrelic-infra.yml
name: my-node-host
license_key: VOTRE_LICENSE_KEY_ICI
interval: 10s
proxy_url: http://proxy.company.com:8080
log_file: /var/log/newrelic-infra.log
log_level: info

integrations:
  - name: nri-mongodb
    config:
      databases:
        - mongodb1
        - mongodb2
  - name: nri-kubernetes
    config: { }

metrics_format: p99

This YAML config monitors the host (CPU, memory) + MongoDB/K8s integrations. 10s interval for high granularity. Place in /etc/newrelic-infra.yml and launch the infra agent. Avoid debug log_level in production (high overhead); metrics_format: p99 focuses on 99th percentile for outliers.

Best Practices

  • Separate ENV by environment: NEW_RELIC_APP_NAME=prod-app and NEW_RELIC_LOG_LEVEL=warn in production to keep overhead <2%.
  • Use NRQL queries: In the UI, query SELECT average(duration) FROM Transaction WHERE appName = 'MonAppNode' SINCE 1 hour ago for custom alerts.
  • Enable Real User Monitoring (RUM): Add JS snippet to frontend for correlating front/back traces.
  • Dashboards with NerdGraph API: Automate via GraphQL for CI/CD.
  • Scale with New Relic One: Link to OpenTelemetry for hybrid tracing.

Common Errors to Avoid

  • Missing license key: App invisible in UI; check newrelic_agent.log for 'License key invalid'.
  • require('newrelic') not first: Incomplete instrumentation, untraced routes.
  • Distributed tracing ENV without headers: Broken cross-service traces; add NEW_RELIC_DISTRIBUTED_TRACING_ENABLED=true.
  • Ignoring slow_sql: Hidden DB bottlenecks; always enable with slow_sql.enabled: true.

Next Steps