Node.js SDK reference
This reference documents every public export of @amplitude/analytics-node and every option you can pass to init(), verified against version 1.5.83. For options, go to Configuration options. To find the release that added or changed a feature, go to Node.js SDK release notes.
import * as amplitude from "@amplitude/analytics-node";
The package exports init, track, logEvent, identify, groupIdentify, setGroup, revenue, add, remove, flush, setOptOut, createInstance, the Identify and Revenue classes, and the Types namespace. The top-level functions act on a default instance. Each instance from createInstance() has the same methods, except createInstance itself.
Return values
Methods that do asynchronous work return AmplitudeReturn<T>, an object with one property, promise. Await promise, not the return value itself.
import { init, track } from "@amplitude/analytics-node";
init("AMPLITUDE_API_KEY");
const result = await track("Song Played", undefined, { user_id: "user-12345" })
.promise; // correct
const wrapper = track("Song Played", undefined, { user_id: "user-12345" }); // { promise }, not a Result
Tracking methods resolve to a Result:
| Field | Type | Description |
|---|---|---|
event | Event | The final event, after plugins ran. |
code | number | The HTTP status, or 0 and 100 for results the SDK produces itself. Go to Read the upload result. |
message | string | A description of the result, such as Event tracked successfully. |
| Method | promise resolves to | When |
|---|---|---|
init(), add(), remove() | void | When the SDK finishes the setup work. |
track(), logEvent(), identify(), groupIdentify(), setGroup(), revenue() | Result | After the upload attempt for the event. |
flush() | void | After the upload that flush() started finishes. It doesn't return per-event results. |
setOptOut() returns nothing.
Setup
init
Initializes the instance with your API key and options. Call it once per instance. Calls you make before it finishes wait in a queue.
init(apiKey: string, options?: NodeOptions): AmplitudeReturn<void>
| Parameter | Type | Description |
|---|---|---|
apiKey | string | Your Amplitude project's API key. |
options | NodeOptions | Optional. Go to Configuration options. |
import { init } from "@amplitude/analytics-node";
await init("AMPLITUDE_API_KEY", { flushIntervalMillis: 5000 }).promise;
Calling init() again on an initialized instance tears down its plugins, then runs setup again.
createInstance
Creates an independent instance with its own configuration, queue, and plugins.
createInstance(): NodeClient
import { createInstance } from "@amplitude/analytics-node";
const client = createInstance();
client.init("AMPLITUDE_API_KEY");
client.track("Button Clicked", undefined, { user_id: "user-12345" });
The instance has init, add, remove, track, logEvent, identify, groupIdentify, setGroup, revenue, flush, and setOptOut.
add
Adds a plugin to the instance. Go to Plugin.
add(plugin: Plugin): AmplitudeReturn<void>
| Parameter | Type | Description |
|---|---|---|
plugin | Plugin | A before, enrichment, or destination plugin. The SDK skips a plugin whose name is already registered. |
remove
Removes a plugin by name and calls its teardown().
remove(pluginName: string): AmplitudeReturn<void>
| Parameter | Type | Description |
|---|---|---|
pluginName | string | The plugin's name. An unknown name logs a warning and changes nothing. |
import { init, add, remove } from "@amplitude/analytics-node";
await init("AMPLITUDE_API_KEY").promise;
await add({ name: "noop", type: "enrichment", execute: async (event) => event })
.promise;
await remove("noop").promise;
flush
Uploads every queued event that isn't waiting on a retry backoff, without waiting for the interval.
flush(): AmplitudeReturn<void>
import { init, track, flush } from "@amplitude/analytics-node";
await init("AMPLITUDE_API_KEY").promise;
track("Button Clicked", undefined, { user_id: "user-12345" });
await flush().promise;
flush() makes one attempt per batch and doesn't retry. Successful events resolve with the message success: followed by the server's response. If a scheduled upload is in progress, flush() does nothing and resolves. Call it after init() resolves. A flush() call that runs earlier discards the queued events with code 100.
Tracking
Every tracking method takes EventOptions as its last argument. Pass user_id or device_id there.
track
Tracks an event. logEvent is an alias.
track(eventInput: BaseEvent | string, eventProperties?: Record<string, any>, eventOptions?: EventOptions): AmplitudeReturn<Result>
| Parameter | Type | Description |
|---|---|---|
eventInput | BaseEvent | string | The event name, or an event object with event_type and any other event fields. |
eventProperties | Record<string, any> | Optional. Event properties. Replaces event_properties on an event object. |
eventOptions | EventOptions | Optional. Event fields, such as user_id. They override the same fields on an event object. |
import { init, track } from "@amplitude/analytics-node";
init("AMPLITUDE_API_KEY");
track("Button Clicked", { buttonColor: "primary" }, { user_id: "user-12345" });
An event_type that's empty, only whitespace, or not a string resolves with 0 and Event skipped due to empty event type without sending. Requires 1.5.70 or later.
identify
Sends an $identify event that updates user properties.
identify(identify: Identify, eventOptions?: EventOptions): AmplitudeReturn<Result>
| Parameter | Type | Description |
|---|---|---|
identify | Identify | The operations to apply. Go to Identify class. |
eventOptions | EventOptions | Optional. Pass user_id or device_id. |
import { init, identify, Identify } from "@amplitude/analytics-node";
init("AMPLITUDE_API_KEY");
identify(new Identify().set("plan", "pro"), { user_id: "user-12345" });
setGroup
Sends an $identify event that adds the user to one or more groups of a type, and sets the group type as a user property.
setGroup(groupType: string, groupName: string | string[], eventOptions?: EventOptions): AmplitudeReturn<Result>
| Parameter | Type | Description |
|---|---|---|
groupType | string | The group type, such as orgId. |
groupName | string | string[] | One group name, or an array of group names. |
eventOptions | EventOptions | Optional. Pass user_id or device_id. |
import { init, setGroup } from "@amplitude/analytics-node";
init("AMPLITUDE_API_KEY");
setGroup("orgId", "15", { user_id: "user-12345" });
groupIdentify
Sends a $groupidentify event that updates a group's properties.
groupIdentify(groupType: string, groupName: string | string[], identify: Identify, eventOptions?: EventOptions): AmplitudeReturn<Result>
| Parameter | Type | Description |
|---|---|---|
groupType | string | The group type. |
groupName | string | string[] | The group name. |
identify | Identify | The operations to apply to group properties. |
eventOptions | EventOptions | Optional. |
import { init, groupIdentify, Identify } from "@amplitude/analytics-node";
init("AMPLITUDE_API_KEY");
groupIdentify("orgId", "15", new Identify().set("plan", "enterprise"), {
user_id: "user-12345",
});
revenue
Sends a revenue_amount event.
revenue(revenue: Revenue, eventOptions?: EventOptions): AmplitudeReturn<Result>
| Parameter | Type | Description |
|---|---|---|
revenue | Revenue | The purchase. Go to Revenue class. |
eventOptions | EventOptions | Optional. Pass user_id or device_id. |
import { init, revenue, Revenue } from "@amplitude/analytics-node";
init("AMPLITUDE_API_KEY");
revenue(new Revenue().setProductId("sku-1").setPrice(9.99), {
user_id: "user-12345",
});
Privacy
setOptOut
Turns sending on or off for the whole instance. The SDK doesn't persist the setting. It lasts until you change it or the process exits.
setOptOut(optOut: boolean): void
| Parameter | Type | Description |
|---|---|---|
optOut | boolean | true skips every later event with Event skipped due to optOut config. false resumes. |
import { init, setOptOut } from "@amplitude/analytics-node";
init("AMPLITUDE_API_KEY");
setOptOut(true);
Plugins with an onOptOutChanged() method receive the new value.
Identify class
Collects user or group property operations. Every method returns the same Identify object, so you can chain calls.
import { init, identify, Identify } from "@amplitude/analytics-node";
init("AMPLITUDE_API_KEY");
const props = new Identify().set("plan", "pro").add("login_count", 1);
identify(props, { user_id: "user-12345" });
| Method | Description |
|---|---|
set(property, value) | Sets the value. |
setOnce(property, value) | Sets the value only if the property has none. |
add(property, value: number) | Adds a number. The SDK ignores a non-number value. |
append(property, value) | Adds values to the end of a list. |
prepend(property, value) | Adds values to the start of a list. |
postInsert(property, value) | Adds values to the end of a list if they're not in it. |
preInsert(property, value) | Adds values to the start of a list if they're not in it. |
remove(property, value) | Removes values from a list. |
unset(property) | Removes the property. |
clearAll() | Removes all properties. The SDK discards operations queued before it and skips later ones. |
getUserProperties() | Returns the operations as an object, such as { "$set": { "plan": "pro" } }. |
Each property accepts one operation per object. The SDK skips a later operation on the same property without a log message. Values must be strings, numbers, booleans, objects, or arrays of strings, numbers, or objects. The SDK skips other values, such as null.
Revenue class
Describes one purchase. Every setter returns the same Revenue object.
| Method | Event property | Description |
|---|---|---|
setProductId(productId) | $productId | The product identifier. Defaults to an empty string. |
setPrice(price) | $price | The unit price. Can be negative, for refunds. Defaults to 0. |
setQuantity(quantity) | $quantity | The number of units. Defaults to 1. The SDK ignores values of 0 or less. |
setRevenue(revenue) | $revenue | The total amount. Overrides price times quantity. |
setRevenueType(revenueType) | $revenueType | A category, such as purchase or refund. |
setCurrency(currency) | $currency | The currency code, such as USD. |
setReceipt(receipt) | $receipt | The receipt identifier. |
setReceiptSig(receiptSig) | $receiptSig | The receipt signature. |
setEventProperties(properties) | Your keys | Other event properties. The $ properties above win on a name conflict. |
getEventProperties() | Returns the event properties the Revenue object produces. |
import { init, revenue, Revenue } from "@amplitude/analytics-node";
init("AMPLITUDE_API_KEY");
const refund = new Revenue()
.setProductId("sku-1")
.setPrice(-9.99)
.setRevenueType("refund")
.setCurrency("USD")
.setReceipt("receipt-8812")
.setReceiptSig("sig-8812");
revenue(refund, { user_id: "user-12345" });
Plugin
A plugin is an object or class instance with these members:
| Member | Type | Description |
|---|---|---|
name | string | Optional. A unique name. Without one, the SDK assigns a random ID and logs a warning. |
type | "before" | "enrichment" | "destination" | Optional for enrichment plugins, which are the default. Required for the other types. |
setup(config, client) | (IConfig, NodeClient) => Promise<void> | Optional. Runs once, when you add the plugin or when init() finishes, whichever is later. |
execute(event) | (Event) => Promise<Event | null> | For before and enrichment plugins. Optional. Return the event, or null to drop it. |
execute(event) | (Event) => Promise<Result> | For destination plugins. Required. Return { event, code, message }. |
flush() | () => Promise<void> | Optional, destination plugins only. Runs when you call flush(). |
teardown() | () => Promise<void> | Optional. Runs when you remove the plugin, or when init() runs again. |
onOptOutChanged(optOut) | (boolean) => Promise<void> | Optional. Runs when setOptOut() changes the value. |
Plugins run in three stages: before, then enrichment, then all destination plugins at once. init() adds the built-in context (before) and amplitude (destination) plugins. For the order rules, go to How plugins run.
The Types namespace exports Types.BeforePlugin, Types.EnrichmentPlugin, Types.DestinationPlugin, and Types.Plugin for TypeScript. They're types only. Since 1.4.0, the plugin type is a string, and Types.PluginType doesn't exist at runtime.
Types
Types is a namespace of TypeScript types plus a few runtime values. In JavaScript, use only the runtime values in the following table.
| Runtime value | Values |
|---|---|
Types.LogLevel | None (0), Error (1), Warn (2), Verbose (3), Debug (4). |
Types.ServerZone | US, EU, STAGING. Deprecated. Pass the string "US" or "EU" instead. |
Types.IdentifyOperation | $set, $setOnce, $add, $append, $prepend, $remove, $preInsert, $postInsert, $unset, $clearAll. |
Types.SpecialEventType | IDENTIFY ($identify), GROUP_IDENTIFY ($groupidentify), REVENUE (revenue_amount). |
Types.RevenueProperty | $productId, $quantity, $price, $revenueType, $currency, $revenue, $receipt, $receiptSig. |
Types.OfflineDisabled | null. |
These names are TypeScript types only and are undefined at runtime: AmplitudeReturn, BaseEvent, Event, EventOptions, IdentifyEvent, GroupIdentifyEvent, IIdentify, IRevenue, ILogger, IConfig, Plugin, BeforePlugin, EnrichmentPlugin, DestinationPlugin, Result, Storage, ServerZoneType, IdentityStorageType, TransportType, NodeClient, and NodeOptions. TransportType and IdentityStorageType describe Browser SDK settings and have no effect in Node.js.
EventOptions
Event fields you can set per call, in the last argument of a tracking method or on an event object.
| Field | Type | Description |
|---|---|---|
user_id | string | The user's ID. Required unless you pass device_id. |
device_id | string | The device's ID. Required unless you pass user_id. |
time | number | When the event happened, in milliseconds since the epoch. Defaults to the time of the call. |
insert_id | string | A unique ID Amplitude uses to deduplicate. Defaults to a random UUID. |
session_id | number | The session start time in milliseconds, to join events to a client session. |
groups | Record<string, string | string[]> | Groups for this event only. |
plan | Plan | Tracking plan information. Defaults to the plan option. |
ingestion_metadata | IngestionMetadata | Ingestion source. Defaults to the ingestionMetadata option. |
ip, country, region, city, dma, location_lat, location_lng | string or number | Location fields. Amplitude derives location from ip when you omit them. |
app_version, version_name, platform, os_name, os_version, language | string | App and platform fields. |
device_brand, device_manufacturer, device_model, carrier, user_agent | string | Device fields. |
idfa, idfv, adid, android_id, android_app_set_id | string | Advertising and platform device IDs. |
price, quantity, revenue, productId, revenueType, currency, receipt, receiptSig | number or string | Revenue fields on the event itself. Prefer revenue(). |
partner_id | string | A partner identifier. |
extra | Record<string, any> | Data for plugins. The SDK removes it before upload. |
event_id, library | number, string | The SDK sets these and overwrites values you pass. |
Storage
The interface for storageProvider. The SDK stores Event[] values.
| Method | Returns | Description |
|---|---|---|
isEnabled() | Promise<boolean> | Whether the storage is usable. |
get(key) | Promise<Event[] | undefined> | Reads a stored value. |
getRaw(key) | Promise<string | undefined> | Reads a stored value as a string. |
set(key, value) | Promise<void> | Writes a value. |
remove(key) | Promise<void> | Deletes a value. |
reset() | Promise<void> | Deletes everything the storage holds. |
Logger
The interface for loggerProvider.
| Method | Description |
|---|---|
enable(logLevel) | The SDK calls it during init() with the logLevel option. |
disable() | Turns logging off. |
log(...args) | Verbose messages. |
warn(...args) | Warnings. |
error(...args) | Errors. |
debug(...args) | Debug messages, such as method invocation details. |
The default logger prefixes each message with Amplitude Logger and filters by level itself.
Configuration options
Pass options as the second argument to init(). Every option is optional.
import { init, track, Types } from "@amplitude/analytics-node";
init("AMPLITUDE_API_KEY", {
flushIntervalMillis: 5000,
flushQueueSize: 100,
logLevel: Types.LogLevel.Warn,
plan: { branch: "main", version: "3" },
ingestionMetadata: { sourceName: "billing-worker", sourceVersion: "2.1.0" },
});
track("Button Clicked", undefined, { user_id: "user-12345" });
Delivery
| Option | Type | Default | Description |
|---|---|---|---|
flushIntervalMillis | number | 10000 | Milliseconds between an event entering an empty queue and the upload. |
flushQueueSize | number | 200 | The most events per request. Caps batch size, and doesn't start an upload early. 0 uses the default. A 413 response halves it for the rest of the instance's life. |
flushMaxRetries | number | 12 | Total upload attempts per event on scheduled uploads, including the first. 0 uses the default. flush() uploads don't retry. |
serverZone | "US" | "EU" | "US" | The data center. "EU" sends to api.eu.amplitude.com. Other values fall back to US. |
serverUrl | string | https://api2.amplitude.com/2/httpapi | The upload URL. Must start with http:// or https://. When set, it replaces the URL from serverZone and useBatch. |
useBatch | boolean | false | Send to the Batch Event Upload API (/batch) instead of HTTP V2. |
requestTimeoutMillis | number | 10000 | The deadline for each upload request, in milliseconds. The SDK retries a timed-out request like a 408. Applies only to the built-in HTTP client. Requires 1.5.70 or later. |
transportProvider | Transport | The built-in HTTP client | A custom HTTP client. Go to Use a custom HTTP client. |
storageProvider | Storage<Event[]> | None | Where unsent events persist. Without it, the queue is in memory only. Go to Storage. |
offline | boolean | null | false | When true, the SDK queues events but doesn't upload them. Requires 1.4.0 or later. |
Data
| Option | Type | Default | Description |
|---|---|---|---|
minIdLength | number | Not set | The shortest user_id or device_id Amplitude accepts. Sent to Amplitude with each upload. Amplitude's default is 5. |
optOut | boolean | false | When true, the SDK skips every event. Change it later with setOptOut(). |
plan | Plan | Not set | Tracking plan information (branch, source, version, versionId), added to every event. |
ingestionMetadata | IngestionMetadata | Not set | sourceName and sourceVersion, added to every event as ingestion_metadata. |
Instance and logging
| Option | Type | Default | Description |
|---|---|---|---|
instanceName | string | $default_instance | A label for the instance. Requires 1.3.0 or later. |
logLevel | LogLevel | Types.LogLevel.Warn | The lowest level the logger prints. Go to Turn on debug logging. |
loggerProvider | Logger | The built-in logger | A custom logger. Go to Logger. |
Options with no effect in Node.js
NodeOptions also accepts enableRequestBodyCompression and identify, inherited from the shared configuration type. The Node.js SDK ignores both: it never compresses request bodies, and it doesn't apply an identify option.
Was this helpful?
For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.