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.

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

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

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.

ts
init(apiKey: string, options?: NodeOptions): AmplitudeReturn<void>
js
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.

ts
createInstance(): NodeClient
js
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.

ts
add(plugin: Plugin): AmplitudeReturn<void>

remove

Removes a plugin by name and calls its teardown().

ts
remove(pluginName: string): AmplitudeReturn<void>
js
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.

ts
flush(): AmplitudeReturn<void>
js
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.

ts
track(eventInput: BaseEvent | string, eventProperties?: Record<string, any>, eventOptions?: EventOptions): AmplitudeReturn<Result>
js
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.

ts
identify(identify: Identify, eventOptions?: EventOptions): AmplitudeReturn<Result>
js
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.

ts
setGroup(groupType: string, groupName: string | string[], eventOptions?: EventOptions): AmplitudeReturn<Result>
js
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.

ts
groupIdentify(groupType: string, groupName: string | string[], identify: Identify, eventOptions?: EventOptions): AmplitudeReturn<Result>
js
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.

ts
revenue(revenue: Revenue, eventOptions?: EventOptions): AmplitudeReturn<Result>
js
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.

ts
setOptOut(optOut: boolean): void
js
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.

js
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" });

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.

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

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.

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.

Storage

The interface for storageProvider. The SDK stores Event[] values.

Logger

The interface for loggerProvider.

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.

js
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

Data

Instance and logging

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.

이 내용이 도움이 되었나요?

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.

이 페이지에서