On this page

Node SDK

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

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 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

This SDK uses the 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.

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.

ts
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();

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 and JavaScript.

Was this helpful?