Loading the Agent

The agent can only instrument a module if it is active before that module is loaded. This page explains the supported ways to load newrelic, how ES module applications differ, what happens during bootstrap, and special cases: bundlers, worker threads, and loading the agent twice.

Loading Methods

Method Command or code When to use
Preload with -r node -r newrelic app.js Recommended for CommonJS apps. Guarantees the agent loads first.
NODE_OPTIONS NODE_OPTIONS='-r newrelic' node app.js When you cannot edit the start command directly (process managers, PaaS).
ESM loader + preload node --import newrelic/esm-loader.mjs -r newrelic app.mjs Applications that use import/export.
First require const newrelic = require('newrelic') as line one of the entry file Only when you cannot control how the process is started.

With the last method, everything required before newrelic is not instrumented. The agent detects this and logs a warning:

The newrelic module must be the first module required.
The following modules were required before newrelic and are not being instrumented:
    express: /app/node_modules/express/index.js

Note: newrelic.instrumentLoadedModule() once retrofitted instrumentation onto already-loaded modules. It is deprecated, scheduled for removal in v15, never worked for ES modules, and now emits a DeprecationWarning. Use -r newrelic instead.

ES Module Applications

ES modules are loaded through a different pipeline, so the agent ships a loader, newrelic/esm-loader.mjs. It uses module.register() to install two hooks:

  • @apm-js-collab/tracing-hooks, configured with the agent's subscriber definitions, which instruments packages through diagnostics_channel;
  • import-in-the-middle, which lets the agent patch exports of ES modules. Packages matching /@openai\/agents.*/ are excluded from this hook.

Start your program with both the loader and the CommonJS preload:

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

Points to remember:

  1. Configuration file format. In a package with "type": "module", a newrelic.js file is parsed as an ES module. The README recommends renaming it to newrelic.cjs. A newrelic.mjs exporting export const config = {...} is also discovered.
  2. Custom instrumentation. Pass isEsm: true in the options of newrelic.instrument() and the related methods. See Custom Instrumentation.
  3. Supported API in ESM apps. The README lists instrument, instrumentConglomerate, instrumentDatastore, instrumentMessages, and instrumentWebframework as supported for ES module apps.

Next.js

The README recommends New Relic's "hybrid agent" approach for Next.js and points to the Next.js instrumentation documentation and an App Router example. The next package is in the instrumented module list (instrumentation.next.enabled).

What Happens at Bootstrap

When newrelic is loaded for the first time, index.js runs the following steps:

  1. Records the process uptime (used for the Nodejs/Application/Opening/Duration supportability metric) and logs the agent and Node.js versions.
  2. Double-load check. If a copy of the agent is already cached in require.cache.__NR_cache, it logs Attempting to load a second copy of newrelic from <dir>, using cache instead and returns the existing API. This is why -r newrelic plus require('newrelic') in your code is safe.
  3. Node.js version check against >=22.16.0; failure stops startup.
  4. Builds the configuration (see Configuration). If building throws (for example on a schema validation error), it prints New Relic for Node.js is disabled due to an error: and the stack to stderr, and continues with a disabled configuration that logs to stdout.
  5. Decides whether to start. Each of these stops startup but still exports the stub API:
    • agent_enabled is false — logs Module disabled in configuration. Not starting.
    • The process is a worker thread and worker_threads.enabled is false.
    • opentelemetry.enabled is true but the @opentelemetry/* packages cannot be resolved — logs OpenTelemetry bridge enabled, but packages are missing. Not starting!
  6. Creates the agent. If no application name resolves, it throws New Relic requires that you name this application! (caught and printed to stderr).
  7. Installs instrumentation hooks, checks for modules loaded too early, and starts connecting. A missing license key (outside serverless mode) makes agent.start fail with Not starting without license key!.
  8. If security.agent.enabled is true, starts @newrelic/security-agent.

The Stub API

Whenever the agent does not start, require('newrelic') returns a stub built from the real API's method names. Every method logs Not calling <name> because New Relic is disabled. at debug level and returns undefined, except:

Method Stub behavior
startSegment(name, record, handler, cb) Calls handler(cb) and returns its result.
startWebTransaction(url, handle) Calls handle() and returns its result.
startBackgroundTransaction(name, group, handle) Calls the handle (also when passed as the second argument).
getTransaction() Returns a stub handle whose methods do nothing (end(cb) still calls cb asynchronously).
getBrowserTimingHeader() Returns an empty string, so templates never render undefined.
getLinkingMetadata() Returns {}.
getTraceMetadata() Returns { traceId: '', spanId: '' }.
setLambdaHandler(handler) Returns the handler unchanged.
shutdown(options, cb) Calls the callback on the next tick (setImmediate).

Your code can therefore call the API unconditionally, in tests or locally without a license key.

Worker Threads

By default the agent refuses to run inside a worker thread:

New Relic for Node.js in worker_threads is not officially supported. Not starting! To bypass this, set `config.worker_threads.enabled` to true in configuration.

Setting worker_threads.enabled: true (or NEW_RELIC_WORKER_THREADS_ENABLED=true) lets it start there, with the warning Attempting to load agent in worker thread. This is not officially supported. Use at your own risk.

Bundlers (webpack)

Bundling instrumented libraries into a single file defeats require hooking. The package exports a helper, newrelic/load-externals, that adds every module the agent instruments to your bundler's externals, so they stay real node_modules imports:

// webpack.config.js
const loadExternals = require('newrelic/load-externals')

module.exports = loadExternals({
  target: 'node',
  externals: [],
  // ...the rest of your configuration
})

The helper only does something when config.target includes node, and it pushes into config.externals, which must already be an array. Its source notes it has only been tested with webpack.

Disabling Individual Instrumentations

Each instrumented package has an instrumentation.<package>.enabled toggle (default true). Disabling one is recorded as the supportability metric Nodejs/Instrumentation/<pkg>/disabled:

exports.config = {
  instrumentation: {
    mongodb: { enabled: false }
  }
}

See the instrumentation settings for the full list and the environment variable caveat.

See Also