---
title: Node.js agent API
source: https://docs.newrelic.com/docs/apm/agents/nodejs-agent/api-guides/nodejs-agent-api
---

New Relic offers several tools to help obtain the information needed to provide useful metrics about your Node.js application. These include:

-   Reading the route names (if used) from the Express and Restify routers
-   Using the API to name the current request, either with simple names or groups of controllers with actions
-   Support rules that are stored in your agent's configuration that can mark requests to be renamed or ignored based on regular expressions matched against the request's raw URLs (also available as API calls)

The number of names that New Relic tracks needs to be small enough so that the user experience is robust. It also needs to be large enough to provide the right amount of information (without overwhelming you with data) so that you can identify problem spots in your applications more easily.

For more information, see the [Node.js agent configuration](https://docs.newrelic.com/docs/agents/nodejs-agent/installation-configuration/nodejs-agent-configuration) documentation, the [Node.js agent API documentation on Github](https://newrelic.github.io/node-newrelic/) and [Node.js agent example applications](https://github.com/newrelic/newrelic-node-examples/tree/main).

## Request names

The Node.js agent captures the HTTP method along with a potentially parameterized path (such as `/user/:id`) or a regular expression (such as `/^/user/([-0-9a-f]+)$/`). These pieces of information become part of the request name.

If you have support for slow transaction traces and have added `'request.parameters.*'` to [`attributes.include`](https://docs.newrelic.com/docs/agents/nodejs-agent/attributes/nodejs-agent-attributes#cfg-attributes-include) in your config file, the transaction trace will also have the request's parameters and their values attached. If you don't like the request names that the Node.js agent uses, you can use API calls to create more descriptive names.

> #### 💡 TIP
>
> If grouping your requests under the generic name, then `/*` is sufficient, and you do not need to customize your configuration file or API calls.

## Requirements [#requirements]

New Relic uses request names to group requests for many charts and tables. The value of these visualizations will drop as the number of different request names increases.

For example, do not include potentially dynamic data like GUIDs, numerical IDs, or timestamps in the request names you create. If your request is slow enough to generate a transaction trace, that trace will contain the original URL. If you enable parameter capture, the parameters will also be attached to the trace.

> #### 💡 TIP
>
> Avoid having more than 50 different transaction names. For example, if you have more than a couple hundred different request names, rethink your naming strategy.

## Avoid metric grouping issues [#metric-grouping]

The request naming API helps New Relic avoid problems with trying to handle too many metrics, which sometimes is referred to as "metric explosion." New Relic has several strategies to deal with these issues; the most severe is simply to add offending applications to your deny list.

The main reason for you to be careful in using these request-naming tools is to prevent that from happening to your applications. For more information, see [Metric grouping issues](https://docs.newrelic.com/docs/apm/other-features/metrics/metric-grouping-issues).

## Guidelines [#rules]

Define your configuration rules from the most specific to the most general. The first rules listed in your config file or added with the [Node.js transaction naming API](https://docs.newrelic.com/docs/nodejs/nodejs-transaction-naming-api) will be applied first and should be narrowly targeted. More general "fall-through" rules should be added toward the end of the list, because they will be evaluated in the order they were configured or added using the Node.js transaction naming API.

**URL pattern matching**

An online retailer has a URL pattern like this:

```
/user/customers/all/prospects
/user/customers/all/current
/user/customers/all/returning
/user/customers/John
/user/customers/Jane
```

The retailer could create rules like this:

```js
// newrelic.js
exports.config={
  //other configuration
  rules:{
    name:[
      { pattern: "/user/customers/all/prospects/", name: "/user/customers/all/prospects" },
      { pattern: "/user/customers/all/.*", name: "/user/customers/all" },
      { pattern: "/user/customers/.*", name: "/user/customers/:customer" }
    ]
  }
};
```

With these rules, the retailer would create three transaction names:

-   `/user/customers/:customer`
-   `/user/customers/all`
-   `/user/customers/all/prospects`

    If the retailer reversed the order, the rules would catch `all` transactions in `:customer`, which would not be as useful.

## Load the API [#loading]

Make sure that loading the New Relic module is the first thing your application does, as it needs to bootstrap itself before the rest of your application loads:

```js
const newrelic = require('newrelic');
```

This returns the New Relic Node.js API. You can safely require the module from multiple modules in your application, as it only initializes itself once.

## Request API calls [#request-api]

Here is a summary of the Request API calls for New Relic's Node.js agent.

-   [setTransactionName](https://newrelic.github.io/node-newrelic/API.html#setTransactionName)
-   [setControllerName](https://newrelic.github.io/node-newrelic/API.html#setControllerName)

## Custom instrumentation API calls [#custom-instrumentation-api]

Use these API calls to [expand your instrumentation with custom instrumentation](https://docs.newrelic.com/docs/agents/nodejs-agent/supported-features/nodejs-custom-instrumentation).

## Custom metrics API calls [#custom-metric-api]

Use these API calls to [record additional arbitrary metrics](https://docs.newrelic.com/docs/agents/nodejs-agent/supported-features/nodejs-custom-metrics).

## Custom events API calls [#custom-events-api]

Use these API calls to record additional events:

-   [recordCustomEvent](https://newrelic.github.io/node-newrelic/API.html#recordCustomEvent)
-   [recordLogEvent](https://newrelic.github.io/node-newrelic/API.html#recordLogEvent)

## Transaction handle methods [#transaction-handle]

Use these API calls to [interact with the current transaction](https://newrelic.github.io/node-newrelic/TransactionHandle.html)

## Rules for naming and ignoring requests [#ignoring]

If you do not want to put calls to the New Relic module directly into your application code, you can use pattern-based rules to name requests. There are two sets of rules: one for renaming requests, and one to mark requests to be ignored by New Relic's instrumentation.

Here is the structure for rules in New Relic's Node.js agent.

**`rules.name`**

A list of rules of the format `{pattern : "pattern", name : "name"}` for matching incoming request URLs to `pattern` and naming the matching New Relic transaction's `name`. This acts as a regex replace, where you can set the pattern either as a string, or as a JavaScript regular expression literal, and both pattern and name are required.

When passing a regex as a string, escape backslashes, as the agent does not keep them when given as a string in a pattern. Define your configuration rules from the most specific to the most general, as the patterns will be evaluated in order and are terminal in nature. For more information, see the [naming guidelines](https://docs.newrelic.com/docs/agents/nodejs-agent/installation-configuration/configuring-nodejs#rules).

This can also be set with the environment variable `NEW_RELIC_NAMING_RULES`, with multiple rules passed in as a list of comma-delimited JSON object literals:

````js
NEW_RELIC_NAMING_RULES='{"pattern":"^t","name":"u"},{"pattern":"^u","name":"t"}'
```

### Optional rules attributes

Additional optional attributes are available:

<table>
  <thead>
    <tr>
      <th style={{ width: "200px" }}>
        <DNT>
          **Optional rules attributes**
        </DNT>
      </th>

      <th>
        <DNT>
          **Description**
        </DNT>
      </th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>
        `terminate_chain`
      </td>

      <td>
        Default: `true`

        When set to `true` (default), no further rules will be evaluated if this rule is a match. Setting this to false is useful when multiple rules should be used together. For example, one rule could be replacing a common pattern in many different URLs, while subsequent rule(s) would be more specific.
      </td>
    </tr>

    <tr>
      <td>
        `replace_all`
      </td>

      <td>
        Default: `false`

        When set to `true`, all matches of the pattern will be replaced. Otherwise, only the first match will be replaced. Using the `g` flag with regular expression literal will have the same effect. For example:

        ```js
        pattern:     '[0-9]+',
        replace_all: true
        ```

        This has the same effect as `pattern: /[0-9]+/g`.
      </td>
    </tr>

    <tr>
      <td>
        `precedence`
      </td>

      <td>
        By default the rules are evaluated in order, from first to last. If you prefer to have complete control over the order, you can give each rule a `precedence` attribute. The precedence is an integer number, and rules are evaluated in ascending order. If `precedence` is not explicitly defined, it will be set to 500 by default.

        Additional attributes are ignored.
      </td>
    </tr>
  </tbody>
</table>

### Testing your naming rules

The Node.js agent comes with a command-line tool for testing naming rules. For more information, run the following command in terminal window in a directory where your app is installed:

```bash
node node_modules/.bin/newrelic-naming-rules
```

### Naming rule examples

Here are some examples of naming rules and the results.

<CollapserGroup>
  <Collapser
    id="naming-full-url"
    title="Match full URL"
  >
    ```js
    pattern: '^/items/[0-9]+$',
    name:    '/items/:id'
    ```

    will result in:

    ```
    /items/123   =>  /items/:id
    /orders/123  =>  /orders/123   (not replaced since the rule is a full match)
    ```
  </Collapser>

  <Collapser
    id="first-match-url"
    title="Replace first match in URL"
  >
    ```js
    pattern: '[0-9]+',
    name:    ':id'
    ```

    will result in:

    ```
    /orders/123            =>  /orders/:id
    /items/123             =>  /items/:id
    /orders/123/items/123  =>  /orders/:id/items/123
    ```
  </Collapser>

  <Collapser
    id="replace-urls"
    title="Replace all matches in any URL"
  >
    ```js
    pattern:     '[0-9]+',
    name:        ':id',
    replace_all: true
    ```

    will result in:

    ```
    /orders/123/items/123  =>  /orders/:id/items/:id
    ```
  </Collapser>

  <Collapser
    id="regular-match-group"
    title="Match group references"
  >
    Using regular expression match group references:

    ```js
    pattern: '^/(items|orders)/[0-9]+$',
    name:    '/\\1/:id'
    ```

    will result in:

    ```
    /orders/123  =>  /orders/:id
    /items/123   =>  /items/:id
    ```
  </Collapser>
</CollapserGroup>

````

**`rules.ignore`**

This can also be set via the environment variable `NEW_RELIC_IGNORING_RULES`, with multiple rules passed in as a list of comma-delimited patterns. Currently there is no way to escape commas in patterns.

````js
NEW_RELIC_IGNORING_RULES='^/socket\.io/\*/xhr-polling,ignore_me'
```

````

Here are full examples of how rules are included in the configuration file:

**Naming rule example**

````js
// newrelic.js
exports.config = {
  // other configuration
  rules : {
    name : [
      { pattern: "/tables/name-here", name: "/name-hererule1" }
    ]
  }
};
```

````

**Ignoring rule example**

If you are using **socket.io**, you will have a use case for ignoring rules right out of the box. To keep socket.io long-polling from dominating your response-time metrics and affecting the Apdex metrics for your application, add a rule such as:

````js
// newrelic.js
exports.config = {
  // other configuration
  rules : {
    ignore : [
      '^\/socket\.io\/.*\/xhr-polling'
    ]
  }
};
```

````

## API calls for rules [#api-calls-rules]

Here are the API calls for naming and ignoring rules with New Relic's Node.js agent.

-   [`addNamingRule`](https://newrelic.github.io/node-newrelic/API.html#addNamingRule)
-   [`addIgnoringRule`](https://newrelic.github.io/node-newrelic/API.html#addIgnoringRule)
