
The Amplitude Node.js SDK is the first backend SDK for Amplitude, written in TypeScript.

Client-side SDKs optimize for tracking session and attribution for a single user or device. The Node SDK focuses on developer experience to help back-end services reliably and correctly send events from many users and sources.

The Node SDK provides:

- Batching of events to send multiple events in the same request.
- Retry handling mechanisms to handle when a network request fails, or when Amplitude throttles or rejects a payload.
- Useful utilities and typing to help debug instrumentation issues.

## Initialize the SDK

Before you instrument, initialize the SDK using the API key for your Amplitude project.
Initialization creates a default instance. You can create more instances using `getInstance` with a string name.

```js
// Option 1, initialize with API_KEY only
Amplitude.init(AMPLITUDE_API_KEY);

// Option 2, initialize including configuration
var options = {};
Amplitude.init(AMPLITUDE_API_KEY, options);
```

## Configure the SDK

| Name                   | Description                                                                                                                                                                                                                                                                                                                                                                                                                                          | Default Value                                                      |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| `debug`                | `boolean`. Whether the SDK starts in debug mode. Debug mode generates logs at WARN level or above when `logLevel` isn't specified.                                                                                                                                                                                                                                                                            | `false`                                                            |
| `logLevel`             | `LogLevel`. Logging verbosity of the SDK. `None` produces no logs. `Error` produces SDK internal errors. `Warn` produces warnings about dangerous or deprecated features. `Verbose` logs all SDK actions.                                                                                                                                                                                                     | `LogLevel.None`                                                    |
| `maxCachedEvents`      | `number`. The maximum events in the buffer.                                                                                                                                                                                                                                                                                                                                                                   | `16000`                                                            |
| `retryTimeouts`        | `number[].` Determines the number of retries for sending failed events and how long each retry waits (ms). An empty array means no retries.                                                                                                                                                                                                                                                                  | `[100, 100, 200, 200, 400, 400, 800, 800, 1600, 1600, 3200, 3200]` |
| `optOut`               | `boolean`. Whether you opt out from sending events.                                                                                                                                                                                                                                                                                                                                                           | `false`                                                            |
| `retryClass`           | `Retry`. The class that handles event retrying.                                                                                                                                                                                                                                                                                                                                                               | `null`                                                             |
| `transportClass`       | `Transport`. The class that transports events.                                                                                                                                                                                                                                                                                                                                                                | `null`                                                             |
| `serverUrl`            | `string`. If you use a proxy server, set its URL here.                                                                                                                                                                                                                                                                                                                                                        | `https://api2.amplitude.com/2/httpapi`                             |
| `uploadIntervalInSec`  | `number`. The events upload interval in seconds.                                                                                                                                                                                                                                                                                                                                                              | `0`                                                                |
| `minIdLength`          | `number`. Optional parameter that sets the minimum permitted length for `user_id` and `device_id` fields.                                                                                                                                                                                                                                                                                                     | `5`                                                                |
| `requestTimeoutMillis` | `number`. Configurable timeout in milliseconds.                                                                                                                                                                                                                                                                                                                                                               | `10000`                                                            |
| `onRetry`              | `(response: Response, attemptNumber: number, isLastRetry: boolean) => boolean)`. @param `response`: Response from the given retry attempt. @param `attemptNumber`: Index in `retryTimeouts` for how long Amplitude waited before this retry attempt. Starts at 0. @param `isLastRetry`: True if `attemptNumber === retryTimeouts.length - 1`. Lifecycle callback that runs after a retry attempt. Called in {@link Retry.sendEventsWithRetry}. | `null`                                                             |

### Configure batching behavior

To support high-performance environments, the SDK sends events in batches. The SDK queues every event the `logEvent` method logs in memory, then flushes events in batches in the background. You can customize batch behavior with `maxCachedEvents` and `uploadIntervalInSec`. By default, the `serverUrl` is `https://api2.amplitude.com/2/httpapi`. To send large batches of data at a time, use batch mode. Set the server URL to the [batch event upload API](/docs/apis/analytics/batch-event-upload) that fits your needs:

- Standard Server Batch API: `https://api2.amplitude.com/batch`.
- EU Residency Server Batch API: `https://api.eu.amplitude.com/batch`.

Both regular mode and batch mode use the same event upload threshold and flush time intervals.

```js
Amplitude.init(AMPLITUDE_API_KEY, {
  // Events queued in memory will flush when number of events exceed upload threshold
  // Default value is 16000
  maxCachedEvents: 20000,
  // Events queue will flush every certain milliseconds based on setting
  // Default value is 0 second.
  uploadIntervalInSec: 10,
});
```

### EU data residency

To send data to Amplitude's EU servers, configure the server URL during initialization.

```js
client = Amplitude.init(AMPLITUDE_API_KEY, {
  serverUrl: "https://api.eu.amplitude.com/2/httpapi",
});
```

## Send events

{% callout type="note" heading="" %}
This SDK uses the [HTTP V2](/docs/apis/analytics/http-v2) API and follows the same constraints for events. Make sure that all events logged in the SDK have the `event_type` field and at least one of `device_id` or `user_id`, and follow the HTTP API's constraints on each of those fields.
{% /callout %}

To prevent instrumentation issues, device IDs and user IDs must be strings with a length of 5 characters or more. If an event contains a device ID or user ID that's too short, Amplitude removes the ID value from the event. If the event doesn't have a `user_id` or `device_id` value, Amplitude may reject the upload with a 400 status. To override the default minimum length of 5 characters, pass the `min_id_length` option with the request.

{% code-group %}
```ts TypeScript
import * as Amplitude from "@amplitude/node";

const client = Amplitude.init(AMPLITUDE_API_KEY);

client.logEvent({
  event_type: "Node.js Event",
  user_id: "datamonster@gmail.com",
  location_lat: 37.77,
  location_lng: -122.39,
  ip: "127.0.0.1",
  event_properties: {
    keyString: "valueString",
    keyInt: 11,
    keyBool: true,
  },
});

// Send any events that are currently queued for sending.
// Will automatically happen on the next event loop.
client.flush();
```

```js JavaScript
// ES5 Syntax
const Amplitude = require("@amplitude/node");
// ES6 Syntax
import * as Amplitude from "@amplitude/node";

var client = Amplitude.init(AMPLITUDE_API_KEY);
client.logEvent({
  event_type: "Node.js Event",
  user_id: "datamonster@gmail.com",
  location_lat: 37.77,
  location_lng: -122.39,
  ip: "127.0.0.1",
  event_properties: {
    keyString: "valueString",
    keyInt: 11,
    keyBool: true,
  },
});

// Send any events that are currently queued for sending.
// Will automatically happen on the next event loop.
client.flush();
```
{% /code-group %}

## Middleware

Middleware lets you extend Amplitude by running a sequence of custom code on every event. The middleware pattern is flexible and supports event enrichment, transformation, filtering, routing to third-party destinations, and more.

Each middleware is a function with this signature:

```js
function (payload: MiddlewarePayload: next: MiddlewareNext): void;
```

The `payload` contains the `event` and an optional `extra` field that lets you pass custom data to your own middleware implementations.

To invoke the next middleware in the queue, use the `next` function. Call `next(payload)` to continue the middleware chain. If a middleware doesn't call `next`, event processing stops after the current middleware completes.

Add middleware to Amplitude through `client.addEventMiddleware()`. You can add as many middleware as you need. Each middleware runs in the order you add it.

```js
const loggingMiddleware: Middleware = (payload, next) => {
 console.log(`[amplitude] event=${payload.event} extra=${payload.extra}`);
 // continue to next middleware in chain
 next(payload);
}

const filteringMiddleware: Middleware = (payload, next) => {
 const {eventType} = payload.event;
 if (shouldSendEvent(eventType)) {
 next(payload)
 } else {
 // event will not continue to following middleware or be sent to Amplitude
 console.log(`Filtered event: ${eventType}`);
 }
}

client.addEventMiddleware(loggingMiddleware)
client.addEventMiddleware(filteringMiddleware)

```

For examples, refer to [TypeScript](https://github.com/amplitude/ampli-examples/tree/main/browser/typescript/v1/react-app/src/middleware) and [JavaScript](https://github.com/amplitude/ampli-examples/tree/main/browser/javascript/v1/react-app/src/middleware).
