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

# Setup guide for Express

> Set up the Apitally SDK for your Express application.

This page guides you through the setup of the Apitally SDK for your [Express](https://expressjs.com) application. If you don't have an Apitally account yet, [sign up](https://app.apitally.io/?signup) before getting started.

Once you're done with this guide, you will be able to:

* Get detailed metrics on API usage, errors, and performance
* Track API adoption and usage by individual consumers
* Log individual API requests, responses, and correlated application logs
* See what's causing slow API requests with traces
* Monitor uptime and set up custom alerts

## Requirements

Requires Node.js 20.6+ and either Express 4.18.2+ or Express 5.x.

## Create app

To get started, create a new app in the [Apitally dashboard](https://app.apitally.io/apps) and select Express as your framework.

![Create app](https://assets.apitally.io/docs/2025-12-08/create-app.webp)

You can also configure the environments (e.g. `prod` and `dev`) for your app, or simply accept the defaults.

After submitting, you will see tailored setup instructions for your app. These include your write token and code snippets you can copy and paste into your project.

> [!NOTE]
>
> The **write token** (`apt_...`) provided in the setup instructions uniquely identifies your app for the purpose of data ingestion only. It does not grant any kind of read access to your data.

## Install the SDK

Install the Apitally SDK as a dependency in your project.

```shell npm theme={null}
npm install apitally
```

```shell yarn theme={null}
yarn add apitally @opentelemetry/api
```

```shell pnpm theme={null}
pnpm add apitally
```

## Initialize Apitally

Import `apitally/express/register` on the first line of your application's entry file, before any other imports. This ensures routes are captured even in routers defined in other modules.

Then call `useApitally` with your Express application, the write token, and other [configuration options](https://docs.apitally.io/sdk-reference/javascript/v1/configuration.md) after creating the app.

```javascript ESM {1,8-11} theme={null}
import "apitally/express/register";

import express from "express";
import { useApitally } from "apitally";

const app = express();

useApitally(app, {
  writeToken: "your-write-token",
  env: "dev", // or "prod" etc.
});

app.use(express.json());
```

```javascript CommonJS {1,8-11} theme={null}
require("apitally/express/register");

const express = require("express");
const { useApitally } = require("apitally");

const app = express();

useApitally(app, {
  writeToken: "your-write-token",
  env: "dev", // or "prod" etc.
});

app.use(express.json());
```

You can also set the `APITALLY_WRITE_TOKEN` and `APITALLY_ENV` environment variables instead of passing `writeToken` and `env` in code.

Deploy your application with these changes, or restart it if you're testing locally.

> [!TIP]
>
> The basic setup is now complete. Metrics and logs will start appearing in the Apitally
> dashboard.

## Identify consumers

Consumers are the users or applications calling your API. Identifying them lets you analyze and filter API traffic by consumer in Apitally.

Call `setConsumer` during request handling to associate the current request with a consumer identifier. You can call it wherever the consumer is known, such as in a route handler, existing middleware, or authentication code.

You can also provide a display name, group, and custom attributes for each consumer.

```javascript Middleware {5-10} theme={null}
import { setConsumer } from "apitally";

app.use((req, res, next) => {
  if (req.user) {
    setConsumer({
      identifier: req.user.username,
      name: req.user.name, // optional
      group: req.user.group, // optional
      attributes: { plan: req.user.plan }, // optional
    });
  }
  next();
});
```

```javascript Route handler {5-10} theme={null}
import { setConsumer } from "apitally";

app.get("/items", (req, res) => {
  if (req.user) {
    setConsumer({
      identifier: req.user.username,
      name: req.user.name, // optional
      group: req.user.group, // optional
      attributes: { plan: req.user.plan }, // optional
    });
  }
  res.json(["item1"]);
});
```

## Capture headers and bodies

Only response headers are captured by default. You can opt in to capture request headers as well as request and response bodies when initializing Apitally.

```javascript {4-6} theme={null}
useApitally(app, {
  writeToken: "your-write-token",
  env: "dev", // or "prod" etc.
  captureRequestHeaders: true,
  captureRequestBody: true,
  captureResponseBody: true,
});
```

## Mask sensitive information

The SDK automatically masks common sensitive query parameters, headers, and body fields.

To mask additional data, pass regular expressions matching query parameter names, header names, or body field names to `maskQueryParams`, `maskHeaders`, or `maskBodyFields`, respectively. Use the `i` flag for case-insensitive matching.

```javascript {3-5} theme={null}
useApitally(app, {
  writeToken: "your-write-token",
  maskQueryParams: [/^account_id$/i],
  maskHeaders: [/^X-Custom-Key$/i],
  maskBodyFields: [/^credit_card$/i],
});
```

You can use the `maskRequestBody` and `maskResponseBody` callbacks to mask individual fields or entire bodies using custom logic. Use `maskLogRecord` to mask or drop application log records.

More information about masking is available [here](https://docs.apitally.io/sdk-reference/javascript/v1/masking.md).

## Sample requests

If your application receives a lot of traffic, you may want to sample requests to stay within your request logs quota. Metrics will continue to count every request regardless of sampling.

Use `sampleRate` to capture logs and traces for a fraction of requests.

```javascript {3} theme={null}
useApitally(app, {
  writeToken: "your-write-token",
  sampleRate: 0.1, // capture logs and traces for 10% of requests
});
```

You can also use the `sampleOnRequest` and `sampleOnResponse` callbacks to make sampling decisions using custom logic.

If your application has an existing OpenTelemetry setup, your tracer provider's sampler also affects which request logs and traces Apitally captures.

More information about sampling is available [here](https://docs.apitally.io/sdk-reference/javascript/v1/sampling.md).

## Instrument third-party libraries

Instrumenting third-party libraries adds details about database queries, HTTP calls to external services, and other operations to your request traces. This lets you see how these operations contribute to API response times.

Use OpenTelemetry instrumentation packages to instrument the libraries you want to trace. For example, to trace database queries made with `pg`, install `@opentelemetry/instrumentation` and `@opentelemetry/instrumentation-pg`:

```shell npm theme={null}
npm install @opentelemetry/instrumentation @opentelemetry/instrumentation-pg
```

```shell yarn theme={null}
yarn add @opentelemetry/instrumentation @opentelemetry/instrumentation-pg
```

```shell pnpm theme={null}
pnpm add @opentelemetry/instrumentation @opentelemetry/instrumentation-pg
```

Create an `instrumentation.mjs` file that registers the instrumentation:

```javascript instrumentation.mjs theme={null}
import { registerInstrumentations } from "@opentelemetry/instrumentation";
import { PgInstrumentation } from "@opentelemetry/instrumentation-pg";

registerInstrumentations({
  instrumentations: [new PgInstrumentation()],
});
```

Load this file before your application code so the instrumentation is registered before `pg` is imported:

```shell theme={null}
node --import ./instrumentation.mjs app.js
```

Apitally sets up OpenTelemetry automatically, so you don't need to create a tracer provider or configure an exporter.

More information about tracing and instrumenting third-party libraries is available [here](https://docs.apitally.io/sdk-reference/javascript/v1/tracing.md).

## Existing OpenTelemetry setup

Apitally works alongside your existing OpenTelemetry instrumentation and exporters. If your application registers its own tracer provider, add `ApitallySpanProcessor` to the list of span processors. For example, with `NodeSDK`:

```javascript {2,7} theme={null}
import { NodeSDK } from "@opentelemetry/sdk-node";
import { ApitallySpanProcessor } from "apitally";

const sdk = new NodeSDK({
  spanProcessors: [
    // your existing span processors ...
    new ApitallySpanProcessor(),
  ],
  // your existing configuration ...
});

sdk.start();
```

> [!WARNING]
>
> If you're using version 10.x of the Sentry JavaScript SDK, add `ApitallySpanProcessor` to the `openTelemetrySpanProcessors` option in `Sentry.init()` and enable Sentry tracing. Sentry's sampling settings also affect which request logs and traces Apitally captures.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.