Skip to content

Node Ampli Wrapper

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

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 and are strongly typed to allow for code completion and compile-time checks.

Ampli Wrapper versus the Amplitude SDK

The Ampli Wrapper is an autogenerated library based on your pre-defined tracking plan. This is a lightweight wrapper over the Amplitude SDK that provides type-safety, automatic code completion, linting, and schema validation. The generated code replicates the spec in the Tracking Plan and enforces its rules and requirements. This guide is about Amplitude SDK. To learn more about Ampli Wrapper, see Ampli Wrapper Overview and examples. Click here for more documentation on Ampli for Node.

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.

Installation

These instructions are also available from the Implementation page of your Amplitude Data workspace.

Install the Ampli CLI

If you haven't installed the Ampli CLI, install it now.

Install dependencies

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

npm install @amplitude/analytics-node
yarn add @amplitude/analytics-node

Pull the SDK into your project

At the project root, run pull command.

ampli pull

This prompts you to log in to your workspace and select a source.

➜ ampli pull sourcename
Ampli project is not initialized. No existing `ampli.json` configuration found.
? Create a new Ampli project here? Yes
Organization: Amplitude
Workspace: My Workspace
Source: sourcename
Runtime: Node.js/TypeScript
Branch: main
Pulling latest version (1.0.0)...
Tracking library generated successfully.
Path: ./src/ampli
➜ ampli pull sourcename
Ampli project is not initialized. No existing `ampli.json` configuration found.
? Create a new Ampli project here? Yes
Organization: Amplitude
Workspace: My Workspace
Source: sourcename
Runtime: Node.js/JavaScript
Branch: main
Pulling latest version (1.0.0)...
Tracking library generated successfully.
Path: ./src/ampli

API

Load

Initialize Ampli in your code. The load() function accepts an options object to configure the SDK's behavior:

Option
Description
disabled Optional. Boolean. 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.
environment Optional. String. Specifies the environment the Ampli Wrapper is running in: production or development.

Environment determines which Access Token is used to load the underlying analytics provider libraries.

Defaults to development.
client.apiKey Optional. String. Specifies an API Key. This option overrides the default, which is the API Key configured in your tracking plan.
client.instance Optional. AmpltitudeClient. Specifies an Amplitude instance. By default Ampli creates an instance for you.
client.configuration Optional. Amplitude.Config. Overrides the default configuration for the AmplitudeClient.

Identify

Call identify() to identify a user in your app and associate all future events with their identity, or to set their properties.

Just as the Ampli Wrapper 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

Note

This feature is available for Growth customers who have purchased 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('userId', groupType', 'groupName');
ampli.setGroup('userId', 'groupType', 'groupName');

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.

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. For example, if Joe is in 'orgId' '10' and '20', then the groupName is '[10, 20]').

Your code might look like this:

ampli.setGroup('userId', 'orgId', ['10', '20']);
ampli.setGroup('userId', '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: EventNameProperties,
  options: EventOptions
)
ampli.eventName(
  userId: string : undefined,
  properties: EventNameProperties,
  options: EventOptions
)

The properties argument passes event properties.

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

For example, in the code snippet below, your tracking plan contains an event called songPlayed. 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 an Amplitude field defined: deviceId. Learn more about Amplitude fields here.

ampli.songPlayed('userId', {
  songId: 'songId', // string,
  songFavorited: true, // boolean
}, {
  deviceId: 'a-device-id',
});
ampli.songPlayed('userId', {
  songId: 'songId', // string,
  songFavorited: true, // boolean
}, {
  deviceId: 'a-device-id',
});

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(new SongPlayed({
  songId: 'songId', // string,
  songFavorited: true, // boolean
}));
ampli.track(new SongPlayed({
  songId: 'songId', // string,
  songFavorited: true, // boolean
}));

Plugin

Plugins allow you to extend the Amplitude behavior, for example, modifying event properties (enrichment type) or sending to a third-party APIs (destination type).

First you need to define your plugin. Enrichment Plugin example:

import { Config, EnrichmentPlugin, Event, PluginType } from '"@amplitude/analytics-node"';

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

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

  /**
   * execute() is called on each event instrumented
   * example: client.track('New Event');
   */
  execute(event: Event): Promise<Event> {
    event.event_id = this.currentId++;
    return event;
  }
}
export class AddEventIdPlugin {
  name = 'add-event-id';
  currentId = 100;

  /**
   * setup() is called on plugin installation
   * example: client.add(new AddEventIdPlugin());
   */
  setup(config) {
     this.config = config;
  }

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

Add your plugin after init Ampli.

ampli.client.add(new AddEventIdPlugin())
ampli.client.add(new AddEventIdPlugin())

Verify implementation status

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

ampli status

To update the implementation status in your tracking plan use the --update flag or -u:

ampli status -u

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.

Migrating from Ampli (Legacy) for the @amplitude/node runtime

Migrate from Ampli for @amplitude/node to Ampli for @amplitude/analytics-node by following these steps.

  1. Update Source runtime.

    In the web app open the Sources page and select the NodeJS Source you want to update. In the modal, change the runtime from TypeScript (Legacy) to TypeScript or JavaScript (Legacy) to JavaScript.

  2. Go to the Implementation page, then select the updated Source for detailed setup and usage instructions.

  3. Remove legacy dependencies from your project.

    yarn remove @amplitude/node

  4. Add new dependencies.

    yarn add @amplitude/analytics-node

  5. Pull the latest Ampli Wrapper.

    ampli pull

  6. Find and replace.

    Middleware is no longer support. It has been replaced by a new Plugin architecture. Migrating from Middleware to a Plugin is easy.

  7. See more details on your Implementation page in the web app.