Ampli for Node SDK

Example

See examples of Ampli implementations for the following languages on GitHub:

The Ampli Wrapper is a generated, strongly typed API for tracking Analytics events based on your Tracking Plan in Amplitude Data. The tracking library exposes a function for every event in your team’s tracking plan. The function’s arguments correspond to the event’s properties.

Ampli can benefit your app by providing autocompletion for events & properties defined in Data and enforce your event schemas in code to prevent bad instrumentation.

Tip

Because JavaScript isn't a type-safe language, static type checking isn't built in like TypeScript. Some common IDEs allow for real-time type checks in JavaScript based on JSDoc.

For a better development experience Ampli generates JSDocs for all methods and classes.

To enable real-time type checking in VSCode for JavaScript:

  1. Go to Preferences > Settings then search for checkJs.
  2. Select JS/TS > Implicit Project Config: Check JS.

After it's activated, type errors appear directly in the IDE.

Jetbrains provides similar support:

  1. Go to Preferences > Editor > Inspections > JavaScript and TypeScript > General.
  2. In Signature mismatch and Type mismatch, set the Severity to Warning or Error based on your desired level of strictness.

Tip

To prevent linting errors for eslint and tslint, the SDK-generated files have the following to disable the linters:

/* tslint:disable */

/* eslint-disable */

There's no corresponding “in-code” functionality with Prettier. Instead, add the generated path/to/ampli to your .prettierignore file. You can get the path with ampli pull. See the Prettier documentation for more information.

Quick start

  1. (Prerequisite) Create a Tracking Plan in Amplitude Data

  2. Install the Amplitude SDK

1npm install @amplitude/node@^1.10.2 @amplitude/identify@^1.10.2 @amplitude/types@^1.10.2
  1. Install the Ampli CLI
1npm install -g @amplitude/ampli
  1. Pull the Ampli Wrapper into your project
1ampli pull [--path ./src/ampli]
  1. Initialize the Ampli Wrapper
1import { ampli } from './src/ampli';
2 
3ampli.load({ client: { apiKey: AMPLITUDE_API_KEY } });
  1. Identify users and set user properties
1ampli.identify('user-id', {
2 userProp: 'A trait associated with this user'
3});
  1. Track events with strongly typed methods and classes
1ampli.songPlayed('ampli-user-id', { songId: 'song-1' });
2ampli.track('ampli-user-id', new SongPlayed({ songId: 'song-2' });
  1. Flush events before application exit
1ampli.flush();
  1. Verify implementation status with CLI
1ampli status [--update]

Install the SDK

If you haven't already, install the core Amplitude SDK dependencies.

1npm install @amplitude/node@^1.10.2 @amplitude/identify@^1.10.2 @amplitude/types@^1.10.2

Install Ampli

You can install the Ampli CLI from Homebrew or NPM.

1npm install -g @amplitude/ampli

1brew tap amplitude/ampli
2brew install ampli

Pull the Ampi wrapper into your project

Run the Ampli CLI pull command to log in to Amplitude Data and download the strongly typed Ampli Wrapper for your tracking plan. Ampli CLI commands are usually run from the project root directory.

1ampli pull

Initialize Ampli

Initialize Ampli in your code.

1import { ampli } from './ampli';
2ampli.load({ client: { apiKey: AMPLITUDE_API_KEY } });

1const { ampli } = require('./ampli');
2ampli.load({ client: { apiKey: AMPLITUDE_API_KEY } });

The load() function requires an options object to configure the SDK's behavior:

Option Type Required Description
disabled Boolean optional Specifies whether the Ampli Wrapper does any work. When true, all calls to the Ampli Wrapper are no-ops. Useful in local or development environments.Defaults to false.
client.instance AmplitudeClient required if client.apiKey isn't set Specifies an Amplitude instance. By default Ampli creates an instance for you.
client.apiKey String required if client.instance isn't set Specifies an API Key. This option overrides the default, which is the API Key configured in your tracking plan.
client.options Amplitude.Options optional Overrides the default configuration for the AmplitudeClient.

Identify

Call identify() to set user properties.

Just as Ampli creates types for events and their properties, it creates types for user properties.

The identify() function accepts an optional userId, optional user properties, and optional options.

For example, your tracking plan contains a user property called role. The property's type is a string.

1ampli.identify('user-id', {
2 role: 'Admin'
3});

The options argument allows you to pass Amplitude fields for this call, such as deviceId.

TypeScriptJavaScript

1ampli.identify('user-id', {
2 role: 'admin'
3}, {
4 deviceId: 'my-device-id'
5});

Group

Call setGroup() to associate a user with their group (for example, their department or company). The setGroup() function accepts a required groupType, and groupName.

1ampli.setGroup('user-id', 'Group name', 'Group Value');

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

Example

For example, if Joe is in 'orgId' '10' and '20', then the groupName is '[10, 20]').

Your code might look like this:

1ampli.setGroup('user-id', 'orgId', ['10', '20']);

Track

To track an event, call the event's corresponding function. Every event in your tracking plan gets its own function in the Ampli Wrapper. The call is structured like this:

1ampli.eventName(
2 userId: string | undefined,
3 properties: EventProperties,
4 options: EventOptions,
5 extra: MiddlewareExtra
6)

userId in multi-tenant, server environments a userId must be provided for each tracking call to associate it to a

properties passes in event properties specific to this event in the tracking plan.

The options argument allows you to pass Amplitude fields, like price, quantity and revenue.

The extra argument lets you pass data to middleware.

For example, your tracking plan contains an event called Song Played. The SDK generates the songPlayed function for the event, using camel case to make it valid JavaScript. The event is defined with two required properties: songId and songFavorited. The property type for songId is string, and songFavorited is a boolean.

The event has two Amplitude fields defined: price, and quantity. Learn more about Amplitude fields here. The event has one MiddlewareExtra defined: myMiddleware. Learn more about middleware.

1ampli.songPlayed('ampli-user-id', {
2 songId: 'songId', // string,
3 songFavorited: true, // boolean
4}, {
5 price: 1.23,
6 quantity: 2
7}, {
8 myMiddleware: { myMiddlewareProp: "value to send to middleware" }
9});

Ampli also generates a class for each event.

1const myEventObject = new SongPlayed({
2 songId: 'songId', // string,
3 songFavorited: true, // boolean
4});

Track Event objects using Ampli track:

1ampli.track('ampli-user-id', new SongPlayed({
2 songId: 'songId', // string,
3 songFavorited: true, // boolean
4}));

Flush

The Ampli wrapper queues events and sends them on an interval based on the configuration.

Call flush() to immediately send any pending events.

The flush() method returns a promise that can be used to ensure all pending events have been sent before continuing.
This can be useful to call prior to application exit.

Ampli flushes events in the buffer automatically when flushQueueSize or flushInterval are reached.

Ampli sends events automatically without calling flush(), but using flush() is useful if you need to send events before the application exits.

1ampli.flush();

Pull

The pull command downloads the Ampli Wrapper code to your project. Run the pull command from the project root.

1ampli pull

You will be prompted to log in to your workspace and select a source.

1ampli pull
2Ampli project is not initialized. No existing `ampli.json` configuration found.
3? Create a new Ampli project here? Yes
4? Organization: Amplitude
5? Workspace: My Workspace
6? Source: My Source

Status

Verify that events are implemented in your code with the status command:

1ampli status [--update]

The output displays status and indicates what events are missing.

1ampli status
2Verifying event tracking implementation in source code
3Song Played (1 location)
4Song Stopped Called when a user stops playing a song.
5Events Tracked: 1 missed, 2 total
Was this page helpful?

Thanks for your feedback!

July 16th, 2024

Need help? Contact Support

Visit Amplitude.com

Have a look at the Amplitude Blog

Learn more at Amplitude Academy

© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.