Node.js

TracesMetricsApp LogsCustom LogsProfiling

This guide provides instructions to set up Application Performance Monitoring (APM) in a Node.js application. You can also find these instructions on the installation page in your Middleware account. For example code, view here.

Prerequisites

  1. Node.js 18.17.1+: Verify with node --version
  2. Python Version 3.8+ Verify with python3 --version

Installation

1 Install Node.js APM Package

Run the following command in your terminal:

2 Setup Options

With Host
Serverless

Host based APM requires the Middleware Agent which can be installed using the relevant OS based instructions. here.

Method 1: Direct Code Initialization

Add the following lines to the beginning of your application code base. The access token is your account key, which can be found on the Installation page.

If you want to track APM data across different deployments of your application. You can pass along the app.version,

For Example, If your deployment version is 1.2.0 the config should look something like this.

Method 2: Add the tracker with command line arguments

Create a file named instrument.js or instrument.ts in your project root:

To ensure the tracker is initialized before any other code runs, use the --require flag when starting your Node.js application:

Method 1: Direct Code Initialization

Add the following lines to the beginning of your application code base. The access token is your account key, which can be found on the Installation page.

If you want to track APM data across different deployments of your application. You can pass along the app.version,

For Example, If your deployment version is 1.2.0 the config should look something like this.

Method 2: Add the tracker with command line arguments

Create a file named instrument.js or instrument.ts in your project root:

To ensure the tracker is initialized before any other code runs, use the --require flag when starting your Node.js application:

3 Container Variables

No Container Variables Required in case of serverless mode

Docker

Applications running in a container require an additional environment variable. If your application is not running in a container, move to Step 4.

For Docker containers, add the following environment variable to your application.

The DOCKER_BRIDGE_GATEWAY_ADDRESS is the IP address of the gateway between the Docker host and bridge network. This is 172.17.0.1 by default. Learn more about Docker bridge networking here

Kubernetes

Then add the following environment variable to your application deployment YAML file.

4 Capture Application Data

Traces

Distributed tracing is automatically enabled upon completion of Step 2.

Span Attributes

For any automatically instrumented endpoints, add the following code snippet:

Custom Logs

To ingest custom logs into Middleware, utilize the following functions inside your logging method based on desired log severity levels.

To add stack traces along with the error log, use the following error tracking function.

Custom Metrics and Spans

Create custom instruments and spans by exposing the meter and tracer with the following pattern:

Profiling

Application Profiling is auto-configured upon completing Step 2.

Stack Traces

Use the errorRecord method to record a stack trace when an error occurs. See an example of this method below.

Continuous Profiling

Continuous profiling captures real-time performance insights. Access this feature under the APM > Continuous Profiling section in the Middleware platform.

Environment Variables

The following environment variables can be used to configure the Middleware APM tracker:

VariableDescriptionPossible Values
MW_TARGETSets the target URLYour Middleware URL
MW_API_KEYSets the access tokenYour Middleware API key
MW_PROJECT_NAMESets the project nameAny string
MW_SERVICE_NAMESets the service nameAny string
MW_APM_TRACES_ENABLEDEnables/disables trace collection"true" or "false"
MW_APM_METRICS_ENABLEDEnables/disables metric collection"true" or "false"
MW_CONSOLE_EXPORTEREnables/disables console exporter"true" or "false"
MW_AGENT_SERVICESets the host for the APM service when using MW AgentValid hostname or IP address
OTEL_NODE_RESOURCE_DETECTORSSpecifies which resource detectors to useComma-separated list (see below)
MW_NODE_DISABLED_INSTRUMENTATIONSSpecifies which instrumentations to disableComma-separated list (see below)

Customizing Resource Detection with OTEL_NODE_RESOURCE_DETECTORS

Specifies which resource detectors to use. Each detector provides specific information about the application's environment.

Default: env, process, host, os, container, serviceinstance

Possible values: env, process, serviceinstance, os, host, container, aws, azure, gcp, none, all

Example: OTEL_NODE_RESOURCE_DETECTORS=env,process,host,aws

Disabling Specific Instrumentations with MW_NODE_DISABLED_INSTRUMENTATIONS

Disables specific instrumentations to exclude certain types of data collection.

Note: File System (fs) instrumentation is permanently disabled due to performance issues.

Possible values: dns, net

Example: MW_NODE_DISABLED_INSTRUMENTATIONS=dns,net

Available instrumentations may vary depending on your Middleware APM version and configuration.

Configuration Options

In addition to using environment variables, you can configure the Middleware APM tracker directly through the tracker.track() call. Here are the configuration options you can use: (env variables have higher priority)

OptionTypeDefaultDescription
targetstringN/ASets the target URL for the APM service
accessTokenstringN/ASets the access token for authentication
projectNamestringN/ASets the project name
serviceNamestringN/ASets the service name
pauseTracesbooleanfalseDisables trace collection
pauseMetricsbooleanfalseDisables metric collection
consoleExporterbooleanfalseEnables console exporter
customResourceAttributesobjectN/ASets custom resource attributes
disabledInstrumentationsstringN/ASpecifies which instrumentations to disable (comma-separated)
consoleLogbooleanfalseEnables consoleLog logs collection
consoleErrorbooleanfalseEnables consoleError logs collection
enableSelfInstrumentationbooleanfalseEnables self-instrumentation for the profiling traces
enableProfilingbooleantrueEnables profiling functionality for performance analysis

Usage Example

Framework-Specific Configuration

If any of the following Nodejs web frameworks are used in your application, configuration steps as per framework is given below.

NestJS

Step 1: Import the Package

In your main.ts, import and configure the tracker:

Step 2: Capture Data

An example of handling errors and logging them:

Graceful Shutdown (Optional)

The Middleware APM tracker provides a sdkShutdown function for graceful shutdown. This ensures all pending telemetry data is sent before your application exits. Call tracker.sdkShutdown() when your application is about to exit to ensure all data is properly flushed.

Usage

Basic Troubleshooting Guidelines

If you're experiencing issues with the Middleware APM tracker or not seeing the expected data, try the following steps:

  1. Enable Debug Logging: Set the DEBUG flag to true in your configuration or use the environment variable to get more detailed logs:

  2. Check Configuration: Ensure all required fields (like serviceName , accessToken , target and accessToken) are correctly set.

  3. Initialize Tracking Function: Make sure your tracker.track() is initialized at the very top of the main server file.

  4. Instrumentation Issues: If specific instrumentations aren't working, check if they're accidentally disabled in your configuration.

  5. Resource Detection: If you're not seeing expected resource attributes, verify your OTEL_NODE_RESOURCE_DETECTORS setting.

  6. Restart Your Application: Sometimes, a simple restart after configuration changes can resolve issues.

  7. Agent Health Check: If you're using the Middleware Agent, the SDK performs a health check at startup. If you see a warning message about the health check failing, it could be due to:

    • Incorrect value of MW_AGENT_SERVICE

    If the problem persists, verify your agent configuration and ensure it's running correctly.

  8. OpenTelemetry Dependency Conflicts: If you're using OpenTelemetry in your application code alongside the Middleware Node SDK, ensure that the versions are compatible. Conflicting versions can lead to unexpected behavior. Check the OpenTelemetry version used by the Middleware SDK (you can find this in the SDK's package.json) and make sure your application's OpenTelemetry dependencies match or are compatible with this version.

If problems persist after trying these steps, please contact Middleware support with your debug logs and configuration details (with sensitive information redacted).

Frequently Asked Questions (FAQ)

node-gyp Failing or Missing Dependencies

If node-gyp fails or dependencies are missing, run the following commands:

Running Apps on Docker

If you're unable to run your Node.js app on Docker, ensure port 9319 is open to allow proper firewall configurations.

Installation successful but no data appears / Existing OpenTelemetry dependency older version issue

If you're seeing the following error, especially when DEBUG: true:

Error: @opentelemetry/api: Registration of version vx.x.x for trace does not match previously registered API vy.y.y

This error occurs due to a version conflict in OpenTelemetry dependencies:

  • Your project (or one of its dependencies) is using OpenTelemetry API older version
  • Our package requires OpenTelemetry API vx.x.x

This version mismatch prevents proper registration of the OpenTelemetry API, which blocks data collection.

Override the older OpenTelemetry API version by explicitly installing vx.x.x:

Docker Image Failing

If your Docker image build is failing, it might be due to missing build dependencies. Add the following lines to your Dockerfile:

These commands install necessary build tools and Python, which are often required for compiling native addons.

ESM Modules Auto-instrumentation not working

If your JavaScript or TypeScript code ( compiled to ES6 Modules (ESM)) and auto-instrumentation isn't working for few libraries.

  1. Install the required package
  1. Use this startup command:

Pyroscope profiling is not available

This warning appears because Pyroscope is an optional dependency that requires system-level build tools. It may fail if:

  • Required system dependencies are missing
  • node-gyp build fails
  • Running in Docker without build essentials
  • Not supported for few machines

Solution For local development, install build dependencies:

For Docker, add build tools in your Dockerfile:

Need assistance or want to learn more about Middleware? Contact our support team in Slack.