On this page

Node.js SDK

The Node.js SDK lets you send events to Amplitude.

Install the SDK

Install the dependency with npm or yarn.

bash
npm install @amplitude/analytics-node

Initialize the SDK

You must initialize the SDK before you instrument it. Initialization requires the API key for your Amplitude project. After you initialize the SDK, you can use it anywhere in your application.

js
import { init } from "@amplitude/analytics-node";

// Option 1, initialize with API_KEY only
init(API_KEY);

// Option 2, initialize including configuration
init(API_KEY, {
  flushIntervalMillis: 30 * 1000, // Sets request interval to 30s
});

Configure the SDK

NameDescriptionDefault Value
instanceNamestring. The instance name.$default_instance
flushIntervalMillisnumber. Sets the interval for uploading events to Amplitude in milliseconds.10,000 (10 seconds)
flushQueueSizenumber. Sets the maximum number of events that Amplitude batches in a single upload attempt.300 events
flushMaxRetriesnumber. Sets the maximum number of retries for failed upload attempts. Applies only to retryable errors.12 times.
logLevelLogLevel.None or LogLevel.Error or LogLevel.Warn or LogLevel.Verbose or LogLevel.Debug. Sets the log level.LogLevel.Warn
loggerProviderLogger. Sets a custom loggerProvider class from the Logger to emit log messages to the destination you choose.Amplitude Logger
minIdLengthnumber. Sets the minimum length for the value of user_id and device_id properties.5
optOutboolean. Sets permission to track events. A value of true prevents Amplitude from tracking and uploading events.false
serverUrlstring. Sets the URL that Amplitude uploads events to.https://api2.amplitude.com/2/httpapi
serverZoneEU or US. Sets the Amplitude server zone. Set this to EU for Amplitude projects created in the EU data center.US
storageProviderStorage<Event[]>. Sets a custom implementation of Storage<Event[]> to persist unsent events.MemoryStorage
transportProviderTransport. Sets a custom implementation of Transport to use a different request API.HTTPTransport
useBatchboolean. Sets whether to upload events to the Batch API instead of the default HTTP V2 API.false

Configure batching behavior

To support high-performance environments, the SDK sends events in batches. The SDK queues every event from the track method in memory and flushes batches in the background. Customize batch behavior with flushQueueSize and flushIntervalMillis. By default, serverUrl is https://api2.amplitude.com/2/httpapi. To send large batches of data at a time, set useBatch to true. Setting useBatch to true sets setServerUrl to the batch event upload API at https://api2.amplitude.com/batch. Both regular mode and batch mode use the same event upload threshold and flush time intervals.

js
import * as amplitude from "@amplitude/analytics-node";

amplitude.init(API_KEY, {
  // Events queued in memory will flush when number of events exceed upload threshold
  // Default value is 30
  flushQueueSize: 50,
  // Events queue will flush every certain milliseconds based on setting
  // Default value is 10000 milliseconds
  flushIntervalMillis: 20000,
});

EU data residency

Configure the server zone when you initialize the client to send data to Amplitude's EU servers. The SDK sends data based on the server zone if you set it.

For EU data residency, set up the project inside Amplitude EU. Initialize the SDK with the API key from Amplitude EU.

js
import * as amplitude from "@amplitude/analytics-node";

amplitude.init(API_KEY, {
  serverZone: amplitude.Types.ServerZone.EU,
});

Debugging

Control the level of logs printed to the developer console.

  • None: Suppresses all log messages.
  • Error: Shows error messages only.
  • Warn: Shows error messages and warnings. This is the default value if you don't explicitly specify logLevel.
  • Verbose: Shows informative messages.
  • Debug: Shows error messages, warnings, and informative messages that may be useful for debugging, including the function context information for all SDK public method invocations. Use this logging mode only in development phases.

Set the log level by configuring logLevel with the level you want.

js
amplitude.init(AMPLITUDE_API_KEY, {
  logLevel: amplitude.Types.LogLevel.Warn,
});

The default logger outputs logs to the developer console. You can provide your own logger implementation based on the Logger interface for any customization purpose. For example, collect any error messages from the SDK in a production environment.

Set the logger by configuring loggerProvider with your own implementation.

js
amplitude.init(AMPLITUDE_API_KEY, {
  loggerProvider: new MyLogger(),
});

Debug mode

Enable debug mode by setting logLevel to "Debug", for example:

js
amplitude.init(AMPLITUDE_API_KEY, {
  logLevel: amplitude.Types.LogLevel.Debug,
});

With the default logger, the SDK outputs extra function context information to the developer console when you invoke any SDK public method, including:

  • type: Category of this context, for example, invoke public method.
  • name: Name of invoked function, for example, setUserId.
  • args: Arguments of the invoked function.
  • stacktrace: Stacktrace of the invoked function.
  • time: Start and end timestamp of the function invocation.
  • states: Useful internal states snapshot before and after the function invocation.

Track an event

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 deviceId (included by default) or userId, 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, the SDK removes the ID value from the event. If the event doesn't have a userId or deviceId value, Amplitude may reject the upload with a 400 status. Override the default minimum length of 5 characters by setting the minIdLength config option.

Events represent how users interact with your application. For example, "Button Clicked" may be an action you want to note.

js
import { track } from "@amplitude/analytics-node";

// Track a basic event
track("Button Clicked", undefined, {
  user_id: "user@amplitude.com",
});

// Track events with optional properties
const eventProperties = {
  buttonColor: "primary",
};
track("Button Clicked", eventProperties, {
  user_id: "user@amplitude.com",
});

Track events to multiple projects

To log events to multiple Amplitude projects, create a separate instance for each Amplitude project. Then, pass the instance variables to wherever you want to call Amplitude. Each instance allows for independent apiKeys, userIds, deviceIds, and settings.

js
import * as amplitude from "@amplitude/analytics-node";

const defaultInstance = amplitude.createInstance();
defaultInstance.init(API_KEY_DEFAULT);

const envInstance = amplitude.createInstance();
envInstance.init(API_KEY_ENV, {
  instanceName: "env",
});

User properties

User properties help you understand your users at the time they performed some action within your app, such as their device details, their preferences, or language.

Identify sets the user properties of a particular user without sending any event. The SDK supports the operations set, setOnce, unset, add, append, prepend, preInsert, postInsert, and remove on individual user properties. Declare the operations through a provided Identify interface. Chain multiple operations together in a single Identify object. Then pass the Identify object to the Amplitude client to send to the server.

If you send the Identify call after the event, the results of operations appear immediately in the dashboard user's profile area, but they don't appear in chart results until you send another event after the Identify call. The Identify call only affects events going forward. Refer to Overview of user properties and event properties in Amplitude for more information.

Set a user property

The Identify object provides controls over setting user properties. First instantiate an Identify object, then call Identify methods on it, and finally have the client make a call with the Identify object.

js
import { identify, Identify } from "@amplitude/analytics-node";

const identifyObj = new Identify();
identify(identifyObj, {
  user_id: "user@amplitude.com",
});

Identify.set

This method sets the value of a user property. For example, you can set a role property of a user.

js
import { Identify, identify } from "@amplitude/analytics-node";

const identifyObj = new Identify();
identifyObj.set("location", "LAX");

identify(identifyObj, {
  user_id: "user@amplitude.com",
});

Identify.setOnce

This method sets the value of a user property only once. The SDK ignores subsequent calls using setOnce(). For example, you can set an initial login method for a user. Because Amplitude only tracks the initial value, setOnce() ignores subsequent calls.

js
import { Identify, identify } from "@amplitude/analytics-node";

const identifyObj = new Identify();
identifyObj.setOnce("initial-location", "SFO");

identify(identifyObj, {
  user_id: "user@amplitude.com",
});

Identify.add

This method increments a user property by some numerical value. If the user property doesn't have a value set yet, the SDK initializes it to 0 before incrementing. For example, you can track a user's travel count.

js
import { Identify, identify } from "@amplitude/analytics-node";

const identifyObj = new Identify();
identifyObj.add("travel-count", 1);

identify(identifyObj, {
  user_id: "user@amplitude.com",
});

Arrays in user properties

You can use arrays as user properties. Set arrays directly, or use prepend, append, preInsert, and postInsert to generate an array.

Identify.prepend

This method prepends a value or values to a user property array. If the user property doesn't have a value set yet, the SDK initializes it to an empty list before prepending the new values.

js
import { Identify, identify } from "@amplitude/analytics-node";

const identifyObj = new Identify();
identifyObj.prepend("visited-locations", "LAX");

identify(identifyObj, {
  user_id: "user@amplitude.com",
});

Identify.append

This method appends a value or values to a user property array. If the user property doesn't have a value set yet, the SDK initializes it to an empty list before appending the new values.

js
import { Identify, identify } from "@amplitude/analytics-node";

const identifyObj = new Identify();
identifyObj.append("visited-locations", "SFO");

identify(identifyObj, {
  user_id: "user@amplitude.com",
});

Identify.preInsert

This method pre-inserts a value or values to a user property if the value doesn't exist in the user property yet. Pre-insert means inserting the value at the beginning of a given list. If the user property doesn't have a value set yet, the SDK initializes it to an empty list before pre-inserting the new values. If the user property has an existing value, this method performs no operation.

js
import { Identify, identify } from "@amplitude/analytics-node";

const identifyObj = new Identify();
identifyObj.preInsert("unique-locations", "LAX");

identify(identifyObj, {
  user_id: "user@amplitude.com",
});

Identify.postInsert

This method post-inserts a value or values to a user property if the value doesn't exist in the user property yet. Post-insert means inserting the value at the end of a given list. If the user property doesn't have a value set yet, the SDK initializes it to an empty list before post-inserting the new values. If the user property has an existing value, this method performs no operation.

js
import { Identify, identify } from "@amplitude/analytics-node";

const identifyObj = new Identify();
identifyObj.postInsert("unique-locations", "SFO");

identify(identifyObj, {
  user_id: "user@amplitude.com",
});

Identify.remove

This method removes a value or values from a user property if the value exists in the user property. Remove means remove the existing value from the given list. If the item doesn't exist in the user property, this method performs no operation.

js
import { Identify, identify } from "@amplitude/analytics-node";

const identifyObj = new Identify();
identifyObj.remove("unique-locations", "JFK");

identify(identifyObj, {
  user_id: "user@amplitude.com",
});

User groups

Amplitude supports assigning users to groups and performing queries, such as Count by Distinct, on those groups. If at least one member of the group has performed the specific event, then the count includes the group.

For example, you want to group your users based on what organization they're in by using an 'orgId'. Joe is in 'orgId' '10', and Sue is in 'orgId' '15'. Sue and Joe both perform a certain event. You can query their organizations in the Event Segmentation Chart.

When you set groups, define a groupType and groupName. In the previous example, 'orgId' is the groupType and '10' and '15' are the values for groupName. Another example of a groupType could be 'sport' with groupName values like 'tennis' and 'baseball'.

Setting a group also sets the groupType:groupName as a user property, and overwrites any existing groupName value set for that user's groupType, and the corresponding user property value. groupType is a string, and groupName can be either a string or an array of strings to indicate that a user is in multiple groups.

If Joe is in 'orgId' '15', then the groupName is '15'.

js
import { setGroup } from "@amplitude/analytics-node";

// set group with a single group name
setGroup("orgId", "15", {
  user_id: "user@amplitude.com",
});

If Joe is in 'sport' 'tennis' and 'soccer', then the groupName is '["tennis", "soccer"]'.

js
import { setGroup } from "@amplitude/analytics-node";

// set group with multiple group names
setGroup("sport", ["soccer", "tennis"], {
  user_id: "user@amplitude.com",
});

You can also set event-level groups by passing an Event Object with groups to track. With event-level groups, the group designation applies only to the specific event Amplitude logs, and doesn't persist on the user unless you explicitly set it with setGroup.

js
import { track } from "@amplitude/analytics-node";

track(
  {
    event_type: "event type",
    event_properties: { eventPropertyKey: "event property value" },
    groups: { orgId: "15" },
  },
  undefined,
  {
    user_id: "user@amplitude.com",
  },
);

Group properties

Use the Group Identify API to set or update the properties of particular groups. These updates only affect events going forward.

The groupIdentify() method accepts a group type and group name string parameter, as well as an Identify object that applies to the group.

js
import { Identify, groupIdentify } from "@amplitude/analytics-node";

const groupType = "plan";
const groupName = "enterprise";
const event = new Identify();
event.set("key1", "value1");

groupIdentify(groupType, groupName, identify, {
  user_id: "user@amplitude.com",
});

Revenue tracking

The preferred method of tracking revenue for a user uses revenue() together with the provided Revenue interface. Revenue instances store each revenue transaction and let you define several special revenue properties (such as "revenueType", "productIdentifier", and so on) that Amplitude's Event Segmentation and Revenue LTV charts use. Pass these Revenue instance objects into revenue() to send as revenue events to Amplitude. This automatically displays data relevant to revenue in the platform. Use this to track both in-app and non-in-app purchases.

To track revenue from a user, call revenue each time a user generates revenue. For example, a customer purchased 3 units of a product at $3.99.

js
import { Revenue, revenue } from "@amplitude/analytics-node";

const event = new Revenue()
  .setProductId("com.company.productId")
  .setPrice(3.99)
  .setQuantity(3);

revenue(event, {
  user_id: "user@amplitude.com",
});

Revenue interface

NameDescription
product_idOptional. String. An identifier for the product. Amplitude recommends something like the Google Play Store product ID. Defaults to null.
quantityRequired. Int. The quantity of products purchased. Note: revenue = quantity * price. Defaults to 1.
priceRequired. Double. The price of the products purchased, which can be negative. Note: revenue = quantity * price. Defaults to null.
revenue_typeOptional, but required for revenue verification. String. The revenue type (for example, tax, refund, income). Defaults to null.
receiptOptional. String. The receipt identifier of the revenue. Defaults to null.
receipt_sigOptional, but required for revenue verification. String. The receipt signature of the revenue. Defaults to null.
propertiesOptional. JSONObject. An object of event properties to include in the revenue event. Defaults to null.

Flush the event buffer

The flush method triggers the client to send buffered events.

js
import { flush } from "@amplitude/analytics-node";

flush();

By default, the SDK calls flush automatically in an interval. To flush the events altogether, control the async flow with the optional Promise interface, for example:

js
await init(AMPLITUDE_API_KEY).promise;
track("Button Clicked", undefined, {
  user_id: "user@amplitude.com",
});
await flush().promise;

Opt users out of tracking

Turn off logging for a given user by setting setOptOut to true.

js
import { setOptOut } from "@amplitude/analytics-node";

setOptOut(true);

While setOptOut is enabled, the SDK doesn't save or send any events to the server, and the setting persists across page loads.

Re-enable logging by setting setOptOut to false.

js
import { setOptOut } from "@amplitude/analytics-node";

setOptOut(false);

Callback

All asynchronous APIs are optionally awaitable through a Promise interface. The Promise interface also serves as a callback interface.

js
import { track } from "@amplitude/analytics-node";

// Using async/await
const results = await track("Button Clicked", undefined, {
  user_id: "user@amplitude.com",
}).promise;
result.event; // {...} (The final event object sent to Amplitude)
result.code; // 200 (The HTTP response status code of the request.
result.message; // "Event tracked successfully" (The response message)

// Using promises
track("Button Clicked", undefined, {
  user_id: "user@amplitude.com",
}).promise.then((result) => {
  result.event; // {...} (The final event object sent to Amplitude)
  result.code; // 200 (The HTTP response status code of the request.
  result.message; // "Event tracked successfully" (The response message)
});

Plugins

Plugins let you extend the Amplitude SDK's behavior by, for example, modifying event properties (enrichment type) or sending to third-party APIs (destination type). A plugin is an object with methods setup() and execute().

Add

The add method adds a plugin to the Amplitude client instance. Plugins can help process and send events.

js
import { add } from "@amplitude/analytics-node";

add(new Plugin());

Remove

The remove method removes the given plugin name from the client instance if it exists.

js
import { remove } from "@amplitude/analytics-node";

remove(plugin.name);

Create a custom plugin

  • plugin.setup()
    • Description: Optional. The setup function is an optional method called when you add the plugin or on first init, whichever happens later. This function accepts two parameters: 1) Amplitude configuration; and 2) Amplitude instance. Use it for setup operations and tasks that depend on either the Amplitude configuration or instance. Examples include assigning baseline values to variables, setting up event listeners, and many more.
  • plugin.execute()
    • Description:
      • Optional for type:enrichment. For enrichment plugins, the execute function is an optional method called on each event. This function must return a new event, otherwise, the SDK drops the passed event from the queue. Use it for cases where you need to add or remove properties from events, filter events, or perform any operation for each event tracked.
      • For destination plugins, the execute function is a required method called on each event. This function must return a response object with keys: event (BaseEvent), code (number), and message (string). Use it to send events to third-party endpoints.

Plugin examples

Here's an example of a plugin that modifies each instrumented event by adding an increment integer to the event_id property of an event starting from 100.

js
import { init, add } from '@amplitude/analytics-node';
import { NodeConfig, EnrichmentPlugin, Event, PluginType } from '@amplitude/analytics-types';

export class AddEventIdPlugin implements EnrichmentPlugin {
  name = 'add-event-id';
  type = PluginType.ENRICHMENT as const;
  currentId = 100;
  config?: NodeConfig;

  /**
   * setup() is called on plugin installation
   * example: client.add(new AddEventIdPlugin());
   */
  async setup(config: NodeConfig): Promise<undefined> {
     this.config = config;
     return;
  }

  /**
   * execute() is called on each event instrumented
   * example: client.track('New Event');
   */
  async execute(event: Event): Promise<Event> {
    event.event_id = this.currentId++;
    return event;
  }
}

init('API_KEY');
add(new AddEventIdPlugin());

Custom HTTP client

You can provide an implementation of the Transport interface to the transportProvider configuration option for customization purposes, for example, sending requests to your proxy server with customized HTTP request headers.

js
import { Transport } from '@amplitude/analytics-types';

class MyTransport implements Transport {
 async send(serverUrl: string, payload: Payload): Promise<Response | null> {
 // check example: https://github.com/amplitude/Amplitude-TypeScript/blob/main/packages/analytics-client-common/src/transports/fetch.ts
 }
}

amplitude.init(API_KEY, {
 transportProvider: new MyTransport(),
});

Was this helpful?