> ## Documentation Index
> Fetch the complete documentation index at: https://docs.honeycomb.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Send Data with the OpenTelemetry JavaScript SDK

> Instrument your Node.js application with the OpenTelemetry JavaScript SDK and send traces, logs, and metrics to Honeycomb.

export const HnyIcon = ({alias, path, size = 16, iconColor}) => {
  const iconMap = {
    "home": "house.svg",
    "marker": "caretFilledDown.svg",
    "show-marker-options": "chatTextLeft.svg",
    "download": "arrowLineDown.svg",
    "trace-waterfall": "trace.svg",
    "show-query-details": "listDashes.svg",
    "table": "table.svg",
    "log-lines": "logLines.svg",
    "chart": "chartLine.svg",
    "show-settings": "gear.svg",
    "add": "plus.svg",
    "remove": "delete.svg",
    "persist": "caretDown.svg",
    "close": "close.svg",
    "copy": "copy.svg",
    "zoom-in": "magnifyingGlassPlus.svg",
    "zoom-out": "magnifyingGlassMinus.svg",
    "color-assignment": "drop.svg",
    "drag": "dots-six-vertical.svg",
    "drawer": "drawer.svg",
    "show-actions": "dotsThree.svg",
    "edit": "pencil.svg",
    "delete": "trash.svg",
    "move": "arrowsOutCardinal.svg",
    "show-legend": "circleInfo.svg",
    "usage-ok": "usageGood.svg",
    "usage-warning": "usageWarning.svg",
    "usage-danger": "usageDanger.svg",
    "open-query-builder": "query.svg",
    "home-menu": "house.svg",
    "query-menu": "query.svg",
    "boards-menu": "board.svg",
    "triggers-menu": "bell.svg",
    "slos-menu": "handshake.svg",
    "service-map-menu": "serviceMap.svg",
    "history-menu": "clockCounterClockwise.svg",
    "manage-data-menu": "cube.svg",
    "usage-menu": "usageGood.svg",
    "show-details": "dotsThreeVertical.svg",
    "resize-handle": "board-panel-resize-handle.png",
    "standard-dataset": "cube.svg",
    "trace-dataset": "cubeChat.svg",
    "all-datasets": "linkedSquares.svg",
    "share": "arrowBentRight.svg",
    "run-in-query-builder": "arrowSquareUpRight.svg",
    "link": "link.svg",
    "text": "text.svg",
    "receive": "arrowLineDown.svg",
    "process": "lightning.svg",
    "sample": "drop.svg",
    "send": "arrowLineUp.svg",
    "submit": "arrowUp.svg",
    "canvas-menu": "sparkle.svg",
    "canvas": "sparkle.svg",
    "private": "lockKey.svg",
    "shared": "people.svg",
    "expand": "caretDown.svg",
    "previous": "caretLeft.svg",
    "next": "caretRight.svg"
  };
  const iconBasePath = "/_assets/icons/";
  const iconPath = path || (alias ? `${iconBasePath}${iconMap[alias]}` : undefined);
  return <span className="hny-icon" style={{
    display: "inline-block",
    width: `${size}px`,
    height: `${size}px`,
    maskImage: `url(${iconPath})`,
    maskSize: "contain",
    maskRepeat: "no-repeat",
    maskPosition: "center",
    WebkitMaskImage: `url(${iconPath})`,
    WebkitMaskSize: "contain",
    WebkitMaskRepeat: "no-repeat",
    WebkitMaskPosition: "center",
    backgroundColor: iconColor || "var(--hny-icon-color)",
    verticalAlign: "middle"
  }} />;
};

export const CalloutLearn = ({children}) => {
  return <Callout icon="brain-circuit" color="#8B5CF6">
      {children}
    </Callout>;
};

Use the OpenTelemetry JavaScript SDK to instrument Node.js applications in a standard, vendor-agnostic, and future-proof way and send telemetry data to Honeycomb.

In this guide, we will walk you through instrumenting with OpenTelemetry for JavaScript, which will include adding automatic instrumentation to your application.

<CalloutLearn>
  For more structured learning, check out the [Instrumentation for OpenTelemetry JavaScript](https://academy.honeycomb.io/app/courses/2ee2544e-866c-4251-90b5-bd17f6e59494) course from Honeycomb Academy.
</CalloutLearn>

## Before You Begin

Before you can set up automatic instrumentation for your Node.js application, you will need to do a few things.

### Prepare Your Development Environment

To complete the required steps, you will need:

* A working Node.js environment
* An application written in Node.js

### Get Your Honeycomb API Key

To send data to Honeycomb, you'll need to [sign up for a free Honeycomb account](https://ui.honeycomb.io/signup) and [create a Honeycomb Ingest API Key](/configure/environments/manage-api-keys/#create-api-key).
To get started, you can create a key that you expect to swap out when you deploy to production.
Name it something helpful, perhaps noting that it's a getting started key.
Make note of your API key; for security reasons, you will not be able to see the key again, and you will need it later!

<Tip>
  For setup, make sure you check the "Can create datasets" checkbox so that your data will show up in Honeycomb. Later, when you replace this key with a permanent one, you can uncheck that box.
</Tip>

If you want to use an API key you previously stored in a secure location, you can also [look up details for Honeycomb API Keys](/configure/environments/manage-api-keys/#find-api-keys) any time in your Environment Settings, and use them to retrieve keys from your storage location.

## Add Automatic Instrumentation

Automatic instrumentation is enabled by adding [instrumentation packages](https://github.com/open-telemetry/opentelemetry-js#instrumentations).
Add custom, or manual, instrumentation using the OpenTelemetry API.

### Acquire Dependencies

<Tabs>
  <Tab title="npm">
    Open your terminal, navigate to the location of your project on your drive, and install OpenTelemetry's automatic instrumentation meta package and OpenTelemetry's Node.js SDK package:

    ```shell theme={}
    npm install --save \
        @opentelemetry/auto-instrumentations-node \
        @opentelemetry/sdk-node
    ```

    | Module                       | Description                                                                                                                                                                                                                     |
    | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | `auto-instrumentations-node` | OpenTelemetry's meta package that provides a way to add automatic instrumentation to any Node application to capture telemetry data from a number of popular libraries and frameworks, like `express`, `dns`, `http`, and more. |
    | `sdk-node`                   | OpenTelemetry's Node.js distribution package that streamlines configuration and allows you to instrument as quickly and easily as possible.                                                                                     |

    Alternatively, install [individual instrumentation packages](https://github.com/open-telemetry/opentelemetry-js#instrumentations).

    If using TypeScript, install `ts-node` to run the code:

    ```shell theme={}
    npm install --save-dev ts-node
    ```
  </Tab>

  <Tab title="yarn">
    Open your terminal, navigate to the location of your project on your drive, and install OpenTelemetry's automatic instrumentation meta package and OpenTelemetry's Node.js SDK package:

    ```shell theme={}
    yarn add \
        @opentelemetry/auto-instrumentations-node \
        @opentelemetry/sdk-node
    ```

    | Module                       | Description                                                                                                                                                                                                                     |
    | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | `auto-instrumentations-node` | OpenTelemetry's meta package that provides a way to add automatic instrumentation to any Node application to capture telemetry data from a number of popular libraries and frameworks, like `express`, `dns`, `http`, and more. |
    | `sdk-node`                   | OpenTelemetry's Node.js distribution package that streamlines configuration and allows you to instrument as quickly and easily as possible.                                                                                     |

    Alternatively, install [individual instrumentation packages](https://github.com/open-telemetry/opentelemetry-js#instrumentations).

    If using TypeScript, install `ts-node` to run the code:

    ```shell theme={}
    yarn add --dev ts-node
    ```
  </Tab>
</Tabs>

### Initialize

<Tabs>
  <Tab title="TypeScript">
    Create an initialization file, commonly known as the `tracing.ts` file:

    ```typescript theme={}
    // Example filename: tracing.ts
    import { NodeSDK } from '@opentelemetry/sdk-node';
    import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';

    const sdk: NodeSDK = new NodeSDK({
      instrumentations: [
        getNodeAutoInstrumentations(),
      ],
    });

    sdk.start();
    ```
  </Tab>

  <Tab title="JavaScript">
    Create an initialization file, commonly known as the `tracing.js` file:

    ```javascript theme={}
    // Example filename: tracing.js
    'use strict';

    const { NodeSDK } = require('@opentelemetry/sdk-node');
    const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');

    const sdk = new NodeSDK({
      instrumentations: [
        getNodeAutoInstrumentations(),
      ],
    });

    sdk.start();
    ```
  </Tab>
</Tabs>

### Configure

Create an `otelconfig.yaml` file with the following content:

```yaml theme={}
file_format: "1.0"

resource:
  attributes:
    - name: service.name
      value: ${OTEL_SERVICE_NAME:-my-service}

tracer_provider:
  processors:
    - batch:
        exporter:
          otlp_http:
            endpoint: https://api.honeycomb.io
            headers:
              - name: x-honeycomb-team
                value: ${HONEYCOMB_API_KEY}

meter_provider: # (*)
  readers:
    - periodic:
        exporter:
          otlp_http:
            endpoint: https://api.honeycomb.io
            headers:
              - name: x-honeycomb-team
                value: ${HONEYCOMB_API_KEY}
              - name: x-honeycomb-dataset
                value: ${HONEYCOMB_METRICS_DATASET}

logger_provider:
  processors:
    - batch:
        exporter:
          otlp_http:
            endpoint: https://api.honeycomb.io
            headers:
              - name: x-honeycomb-team
                value: ${HONEYCOMB_API_KEY}

propagator:
  composite:
    - tracecontext:
    - baggage:
```

Fields marked with an asterisk (\*) are required for exporting metrics to Honeycomb.

Set the following environment variables before running your application:

| Environment Variable        | Value                                         |
| :-------------------------- | :-------------------------------------------- |
| `HONEYCOMB_API_KEY`         | Your Honeycomb API key                        |
| `OTEL_SERVICE_NAME`         | The name of your service                      |
| `HONEYCOMB_METRICS_DATASET` | The Honeycomb dataset to send metrics to (\*) |

<Note>
  If you are using the EU instance, replace `https://api.honeycomb.io` with `https://api.eu1.honeycomb.io` in the configuration file.
</Note>

You can also configure the SDK using [environment variables](https://opentelemetry.io/docs/languages/sdk-configuration/general/).

<Note>
  If you use [Honeycomb Classic](/troubleshoot/product-lifecycle/recommended-migrations/#migrate-from-honeycomb-classic-to-honeycomb-environments), you must also specify the Dataset for traces using the `x-honeycomb-dataset` header:

  ```yaml theme={}
  headers:
    - name: x-honeycomb-team
      value: ${HONEYCOMB_API_KEY}
    - name: x-honeycomb-dataset
      value: your-dataset
  ```
</Note>

<Note>
  If you are sending data directly to Honeycomb, you must configure the API key and service name.
  If you are using an [OpenTelemetry Collector](/send-data/opentelemetry/collector/), configure your API key at the Collector level instead.
</Note>

### Run

<Tabs>
  <Tab title="TypeScript">
    Point the SDK at your configuration file using the `OTEL_CONFIG_FILE` environment variable, then run the Node.js app with the initialization file:

    ```shell theme={}
    OTEL_CONFIG_FILE=./otelconfig.yaml ts-node -r ./tracing.ts YOUR_APPLICATION_NAME.ts
    ```

    Be sure to replace `YOUR_APPLICATION_NAME` with the name of your application's main file.

    Alternatively, you can import the initialization file as the first step in your application lifecycle.

    In Honeycomb's UI, you should now see your application's incoming requests and outgoing HTTP calls generate traces.
  </Tab>

  <Tab title="JavaScript">
    Point the SDK at your configuration file using the `OTEL_CONFIG_FILE` environment variable, then run the Node.js app with the initialization file:

    ```shell theme={}
    OTEL_CONFIG_FILE=./otelconfig.yaml node -r ./tracing.js YOUR_APPLICATION_NAME.js
    ```

    Be sure to replace `YOUR_APPLICATION_NAME` with the name of your application's main file.

    Alternatively, you can import the initialization file as the first step in your application lifecycle.

    In Honeycomb's UI, you should now see your application's incoming requests and outgoing HTTP calls generate traces.
  </Tab>
</Tabs>

## Add Custom Instrumentation

Automatic instrumentation is the easiest way to get started with instrumenting your code.
To get additional insight into your system, you should also add custom, or manual, instrumentation where appropriate.

Follow the instructions below to add custom instrumentation to your code.

To learn more about custom, or manual, instrumentation, visit the comprehensive set of topics covered by [Manual Instrumentation for JavaScript](https://opentelemetry.io/docs/languages/js/instrumentation/) in OpenTelemetry's documentation.

### Acquire Dependencies

To start adding custom instrumentation, ensure that the OpenTelemetry API package exists as a direct dependency in your project.
This package provides access to the high-level instrumentation APIs, which gives the ability to retrieve the current span to enrich with additional attributes, to create new spans, and to generate metrics.

<CodeGroup>
  ```shell npm theme={}
    npm install --save @opentelemetry/api
  ```

  ```shell yarn theme={}
    yarn add @opentelemetry/api
  ```
</CodeGroup>

### Add Attributes to Spans

Adding attributes to a currently executing span in a trace can be useful.
For example, you may have an application or service that handles users, and you want to associate the user with the span when querying your service in Honeycomb.
To do this, get the current span from the context and set an attribute with the user ID:

<CodeGroup>
  ```typescript TypeScript theme={}
    import { trace } from '@opentelemetry/api';

    function handleUser(user) {
      let activeSpan = trace.getActiveSpan();
      activeSpan.setAttribute("user.id", user.getId());
    }
  ```

  ```javascript JavaScript theme={}
    const { trace } = require("@opentelemetry/api");

    function handleUser(user) {
      let activeSpan = trace.getActiveSpan();
      activeSpan.setAttribute("user.id", user.getId());
    }
  ```
</CodeGroup>

This will add a `user.id` field to the current span, so you can use the field in `WHERE`, `GROUP BY` or `ORDER` clauses in the Honeycomb query builder.

### Initialize a Tracer

To create spans, you need to initialize a `Tracer`.

<CodeGroup>
  ```typescript TypeScript theme={}
    import  { trace } from '@opentelemetry/api';

    const tracer = trace.getTracer("tracer.name.here");
  ```

  ```js JavaScript theme={}
    const { trace } = require("@opentelemetry/api");

    const tracer = trace.getTracer("tracer.name.here");
  ```
</CodeGroup>

When you create a `Tracer`, OpenTelemetry requires you to give it a name as a string.
This string is the only required parameter.

When traces are sent to Honeycomb, the name of the `Tracer` is turned into the `library.name` field, which can be used to show all spans created from a particular tracer.

In general, pick a name that matches the appropriate scope for your traces.
If you have one tracer for each service, then use the service name.
If you have multiple tracers that live in different "layers" of your application, then use the name that corresponds to that "layer".

The `library.name` field is also used with traces created from instrumentation libraries.

You can then use this tracer to create custom spans.

### Create New Spans

Automatic instrumentation can show the shape of requests to your system, but only you know the truly important parts.
To get the full picture of what is happening, you must add custom, or manual, instrumentation and create some custom spans.
To do this, grab the tracer from the OpenTelemetry API:

<CodeGroup>
  ```typescript TypeScript theme={}
    import { trace } from '@opentelemetry/api';

    const tracer = trace.getTracer("my-service-tracer");

    function runQuery() {
      tracer.startActiveSpan("expensive-query", (span) => {
        // ... do cool stuff
        span.end();
      });
    }
  ```

  ```javascript JavaScript theme={}
    const { trace } = require("@opentelemetry/api");

    const tracer = trace.getTracer("my-service-tracer");

    function runQuery() {
      tracer.startActiveSpan("expensive-query", (span) => {
        // ... do cool stuff
        span.end();
      });
    }
  ```
</CodeGroup>

### Add Multi-Span Attributes

Sometimes you want to add the same attribute to many spans within the same trace.
This attribute may include variables calculated during your program, or other useful values for correlation or debugging purposes.

To add this attribute to multiple spans, leverage the OpenTelemetry concept of [baggage](https://opentelemetry.io/docs/concepts/signals/baggage/).
Baggage allows you to add a `key` with a `value` as an attribute to every subsequent child span within the current application context.

1. Install the baggage span processor package using your terminal:

   ```shell theme={}
   npm install --save @opentelemetry/baggage-span-processor
   ```

2. When configuring the OpenTelemetry SDK tracer provider, add the `BaggageSpanProcessor`:

   ```javascript theme={}
   import { BaggageSpanProcessor } from "@opentelemetry/baggage-span-processor";

   const sdk = new NodeSDK({
     // ...
     processors: [ new BaggageSpanProcessor() ]
   });
   ```

3. Add a baggage entry for the current trace and replace `key` and `value` with your desired key-value pair:

   <CodeGroup>
     ```typescript TypeScript theme={}
     import {
       Context,
       context,
       propagation,
     } from '@opentelemetry/api';

     tracer.startActiveSpan('main', (span) => {
       span.setAttribute('key', 'value'); // add to current span

       // new context based on current, with key/values added to baggage
       const ctx: Context = propagation.setBaggage(
         context.active(),
         propagation.createBaggage({ 'key': { value: 'value' } })
       );

       // within the new context, do some work and baggage will be
       // applied as attributes on child spans
       context.with(ctx, () => {
         tracer.startActiveSpan('childSpan', (childSpan) => {
           doTheWork();
           childSpan.end();
         });
       });

       span.end();
     });
     ```

     ```javascript JavaScript theme={}
     tracer.startActiveSpan('main', (span) => {
       span.setAttribute('key', 'value'); // add to current span

       // new context based on current, with key/values added to baggage
       const ctx = propagation.setBaggage(
         context.active(),
         propagation.createBaggage({ 'key': { value: 'value' } })
       );

       // within the new context, do some work and baggage will be
       // applied as attributes on child spans
       context.with(ctx, () => {
         tracer.startActiveSpan('childSpan', (childSpan) => {
           doTheWork();
           childSpan.end();
         });
       });

       span.end();
     });
     ```
   </CodeGroup>

   <Note>
     Any Baggage attributes that you set in your application will be attached to outgoing network requests as a header. If your service communicates to a third party API, do **NOT** put sensitive information in the Baggage attributes.
   </Note>

## Sampling

You can configure the OpenTelemetry SDK to [sample the data](/manage-data-volume/sample/guidelines/) it generates.
Honeycomb [weights sampled data based on sample rate](/manage-data-volume/sample/sampled-data-in-honeycomb/), so you must set a resource attribute containing the sample rate.

Use a [`TraceIdRatioBased` sampler](https://opentelemetry.io//docs/specs/otel/trace/sdk/#traceidratiobased), with a ratio expressed as `1/N`.
Then, also create a resource attribute called `SampleRate` with the value of `N`.
This allows Honeycomb to reweigh scalar values, like counts, so that they are accurate even with sampled data.

In the example below, our goal is to keep approximately half (1/2) of the data volume.
The resource attribute contains the denominator (2), while the OpenTelemetry sampler argument contains the decimal value (0.5).

To get access to a sampler, install the core OpenTelemetry package:

```shell theme={}
npm install --save @opentelemetry/core
```

Import the `TraceIdRatioBasedSampler`, and add as a sampler to the `NodeSDK` along with the `SampleRate` in the `Resource`.

```javascript theme={}
// tracing.js
const { TraceIdRatioBasedSampler } = require("@opentelemetry/sdk-trace-node");

const sdk = new NodeSDK({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: "<YOUR_SERVICE_NAME>",
    SampleRate: 2,
  }),
  traceExporter,
  instrumentations: [getNodeAutoInstrumentations()],
  sampler: new TraceIdRatioBasedSampler(0.5),
});
```

## Choosing between gRPC and HTTP

Most OpenTelemetry SDKs have an option to export telemetry as OTLP either over gRPC or HTTP/protobuf, with some also offering HTTP/JSON.
If you are trying to choose between gRPC and HTTP, keep in mind:

* Some SDKs default to using gRPC, and it may be easiest to start with the default option.
* Some firewall policies are not set up to handle gRPC and require using HTTP.
* gRPC may improve performance, but its long-lived connections may cause problems with load balancing, especially when using Refinery.

gRPC default export uses port 4317, whereas HTTP default export uses port 4318.

## Endpoint URLs for OTLP/HTTP

When using the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable with an SDK and an HTTP exporter, the final path of the endpoint is modified by the SDK to represent the specific signal being sent.

For example, when exporting trace data, the endpoint is updated to append `v1/traces`.
When exporting metrics data, the endpoint is updated to append `v1/metrics`.
So, if you were to set the `OTEL_EXPORTER_OTLP_ENDPOINT` to `https://api.honeycomb.io`, traces would be sent to `https://api.honeycomb.io/v1/traces` and metrics would be sent to `https://api.honeycomb.io/v1/metrics`.

The same modification is not necessary for gRPC.

```shell theme={}
export OTEL_EXPORTER_OTLP_ENDPOINT=https://api.honeycomb.io # US instance
#export OTEL_EXPORTER_OTLP_ENDPOINT=https://api.eu1.honeycomb.io # EU instance
```

If the desired outcome is to send data to a different endpoint depending on the signal, use `OTEL_EXPORTER_OTLP_<SIGNAL>_ENDPOINT` instead of the more generic `OTEL_EXPORTER_OTLP_ENDPOINT`.

When using a signal-specific environment variable, these paths must be appended manually.
Set `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` for traces, appending the endpoint with `v1/traces`, and `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` for metrics, appending the endpoint with `v1/metrics`.

Send both traces and metrics to Honeycomb using this method by setting the following variables:

```shell theme={}
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.honeycomb.io/v1/traces # US instance
#export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.eu1.honeycomb.io/v1/traces # EU instance

export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://api.honeycomb.io/v1/metrics # US instance
#export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://api.eu1.honeycomb.io/v1/metrics # EU instance
```

More details about endpoints and signals can be found in the [OpenTelemetry Specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md).

To configure the endpoint URL and API key in code instead of with environment variables, specify `/v1/traces` like so:

```javascript theme={}
// Configure OTLPTraceExporter
const traceExporter =
  new OTLPTraceExporter({
    url: "https://api.honeycomb.io/v1/traces", // US instance
    //url: "https://api.eu1.honeycomb.io/v1/traces", // EU instance
    headers: {
      "x-honeycomb-team": 'your-api-key',
    },
  });
```

## Troubleshooting

To explore common issues when sending data, visit [Common Issues with Sending Data in Honeycomb](/troubleshoot/common-issues/sending-data/#opentelemetry-sdks-and-honeycomb-distributions).
