Skip to content

Node.js Ampli Wrapper

Overview

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.

Amplitude Data supports tracking analytics events from Node.js apps written in JavaScript (ES6 and higher) and TypeScript (2.1 and higher). The generated tracking library is packaged as a CJS module.

Ampli Wrapper versus the Amplitude SDK

We recommend using the Ampli wrapper for all the benefits mentioned above. However, if you want to send events without creating a tracking plan in Amplitude Data, you can learn more about the underlying Amplitude SDK in our SDK Quickstart Guide. Click here for more documentation on the Amplitude Node SDK.

Deprecated Itly runtime

This page covers Node.js JavaScript and TypeScript runtimes. All (Itly) runtimes are deprecated. If you are still using an (Itly) runtime, see the migration guide to upgrade to the newest runtime. Docs for the Itly version are available here.

Beta SDK not supported

The Beta SDK doesn't yet support the Ampli Wrapper. If you use Ampli please continue to use the non-Beta SDK at this time.

Enable type checking

Because JavaScript is not 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.
Linting with Prettier

To prevent linting errors for eslint and tslint, the SDK-generated files have the following to diasable 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

    Plan your events and properties in Amplitude Data. See detailed instructions here

  2. Install the Amplitude SDK

    npm install @amplitude/node @amplitude/identify @amplitude/types
    
  3. Install the Ampli CLI

    npm install -g @amplitude/ampli
    
  4. Pull the Ampli Wrapper into your project

    ampli pull [--path ./src/ampli]
    
  5. Initialize the Ampli Wrapper

    import { ampli } from './src/ampli';
    
    ampli.load({ environment: 'production' });
    
  6. Identify users and set user properties

    ampli.identify('user-id', {
        userProp: 'A trait associated with this user'
    });
    
  7. Track events with strongly typed methods and classes

    ampli.songPlayed('ampli-user-id', { songId: 'song-1' });
    ampli.track('ampli-user-id', new SongPlayed({ songId: 'song-2' });
    
  8. Flush events before application exit

    ampli.flush();
    
  9. Verify implementation status with CLI

    ampli status [--update]
    

Installation

Install the Amplitude SDK

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

npm install @amplitude/node @amplitude/identify @amplitude/types

Install the Ampli CLI

You can install the Ampli CLI from Homebrew or NPM.

brew tap amplitude/ampli
brew install ampli
npm install -g @amplitude/ampli

Pull the Ampli 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.

ampli pull

API

Load

Initialize Ampli in your code.

const { ampli } = require('./ampli');
ampli.load({ environment: 'production' });
import { ampli } from './ampli';
ampli.load({ environment: 'production' });

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

Option
Type Required Description
environment Required. String. Specifies the environment the Ampli Wrapper is running in e.g. production or development. Environments can be created, renamed, and managed in Amplitude Data.

Environment determines which API token is used when sending events.

If an client.apiKey or client.instance is provided, environment will be ignored, and can be omitted.
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.apiKey String optional Specifies an API Key. This option overrides the default, which is the API Key configured in your tracking plan.
client.instance AmplitudeClient optional Specifies an Amplitude instance. By default Ampli creates an instance for you.
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.

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

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

ampli.identify('user-id', {
  role: 'admin'
}, {
  deviceId: 'my-device-id'
});
ampli.identify('user-id', {
  role: 'admin'
}, {
  deviceId: 'my-device-id'
});

Group

Feature availability

This feature is available in accounts with a Growth or Enterprise plan with the Accounts add-on.

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

ampli.setGroup('user-id', 'Group name', 'Group Value');
ampli.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:

ampli.setGroup('user-id', 'orgId', ['10', '20']);
ampli.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:

ampli.eventName(
    userId: string | undefined,
    properties: EventProperties,
    options: EventOptions,
    extra: MiddlewareExtra
)
ampli.eventName(
    userId: string | undefined,
    properties: EventNameProperties,
    options: EventOptions,
    extra: MiddlewareExtra
)

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, quanity 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.

ampli.songPlayed('ampli-user-id', {
  songId: 'songId', // string,
  songFavorited: true, // boolean
}, {
  price: 1.23,
  quantity: 2
}, {
  myMiddleware: { myMiddlewareProp: "value to send to middleware" }
});
ampli.songPlayed('ampli-user-id', {
  songId: 'songId', // string,
  songFavorited: true, // boolean
}, {
  price: 1.23,
  quantity: 2
}, {
  myMiddleware: { myMiddlewareProp: "value to send to middleware" }
});

Ampli also generates a class for each event.

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

Track Event objects using Ampli track:

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

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.flush();
ampli.flush();

Ampli CLI

Pull

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

ampli pull

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

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

Learn more about ampli pull.

Status

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

ampli status [--update]

The output displays status and indicates what events are missing.

➜ ampli status
✘ Verifying event tracking implementation in source code
 ✔ Song Played (1 location)
 ✘ Song Stopped Called when a user stops playing a song.
Events Tracked: 1 missed, 2 total

Learn more about ampli status.

Migrate from an Itly runtime

Migrate from an Itly Node.js runtime to Ampli by following these steps.

  1. Update Source runtime. In the web app open the Connections > Source modal. From the dropdown, update the source to a non-(Itly) runtime.
  2. Follow steps on this page for detailed setup and usage instructions.
  3. Remove legacy Itly dependencies from your project. This includes anything that contains @itly:

    yarn remove @itly/sdk @itly/plugin-schema-validator @itly/plugin-amplitude-node ... 4. Add Amplitude dependencies:

    yarn add @amplitude/node

  4. Pull the latest Ampli Wrapper:

    ampli pull

  5. Check your Ampli Wrapper path.

    ampli pull prints the download location of the SDK. If the path contains itly, you can update the Path by hand in the ampli.json file, or pull again using the --path parameter: ampli pull -p ./path/to/ampli.

  6. Find and replace:

    • import { itly } from '../itly' => import { ampli } from '../ampli'
    • itly.group(userId, groupId) => ampli.setGroup(userId, groupType, groupName)
    • itly.load() => ampli.load()
    • All itly. with ampli.
  7. See updated Event tracking details on your Implementation page in the web app.

Still have questions? Ask them in the Community.