On this page

Node.js Ampli Wrapper

Ampli supports Node.js apps written in JavaScript (ES6 and higher) and TypeScript (2.1 and higher). Ampli packages the generated tracking library as a CJS module.

Enable real-time type checking for JavaScript

Because JavaScript isn't a type-safe language, static type checking isn't built in like TypeScript. Some common IDEs support 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 you activate it, 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 the level of strictness you want.

Linting with Prettier

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

/* tslint:disable */

/* eslint-disable */

Prettier doesn't have a corresponding "in-code" disable directive. Instead, add the generated path/to/ampli to your .prettierignore file. To get the path, run ampli pull. For more information, refer to the Prettier documentation.

Quickstart

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

    Plan your events and properties in Amplitude Data.

  2. Install the Amplitude SDK

    bash
    npm install @amplitude/analytics-node
    
  3. Install the Ampli CLI

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

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

    js
    import { ampli } from "./src/ampli";
    
    ampli.load({ client: { apiKey: AMPLITUDE_API_KEY } });
    
  6. Identify users and set user properties

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

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

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

    shell
    ampli status [--update]
    

Install the Amplitude SDK

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

bash
npm install @amplitude/analytics-node

Install the Ampli CLI

You can install the Ampli CLI from Homebrew or NPM.

bash
brew tap amplitude/ampli
brew install 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. Run Ampli CLI commands from the project root directory.

bash
ampli pull

API

Ampli generates a thin facade over the Amplitude SDK that provides convenience methods. The Ampli Wrapper also grants access to every method of the underlying Amplitude SDK through ampli.client. For more information, refer to Wrapping the Amplitude SDK.

Load

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

The following example initializes with load to override the default configuration:

typescript
ampli.load({
  client: {
    apiKey: AMPLITUDE_API_KEY,
    configuration: {
      minIdLength: 10,
    },
  },
});

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.

typescript
ampli.identify("user-id", {
  role: "admin",
});

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

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

Group

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

ts
ampli.client.setGroup("groupType", "groupName");

Amplitude assigns users to groups and runs queries, such as Count by Distinct, on those groups. If at least one member of the group has performed the specific event, the count includes the group.

For example, you want to group your users by organization 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 you set groups, define a groupType and groupName. In the example above, 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 groupType:groupName as a user property. Amplitude overwrites any existing groupName value for that user's groupType and the corresponding user property value. groupType is a string. groupName can be a string or an array of strings to show that a user belongs to multiple groups. For example, if Joe is in orgId 10 and 20, the groupName is [10, 20].

Your code might look like this:

ts
ampli.client.setGroup("orgId", ["10", "20"]);

Track

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

ts
ampli.eventName(properties: EventNameProperties, options: EventOptions)

The properties argument passes event properties.

The options argument passes Amplitude fields such as price, quantity, and revenue.

For example, in the following code, your tracking plan contains an event called songPlayed. The event has two required properties: songId and songFavorited. The property type for songId is string, and songFavorited is a boolean.

The event defines an Amplitude field: deviceId. For more information about Amplitude fields, refer to the HTTP V2 API event array keys reference.

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

Ampli also generates a class for each event.

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

Track Event objects using Ampli track:

ts
ampli.track(
  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 you can use to ensure all pending events send before continuing. Call flush() before application exit.

typescript
ampli.flush();

Plugin

Plugins extend Amplitude behavior. For example, plugins can modify event properties (enrichment type) or send to third-party APIs (destination type).

First, define your plugin.

typescript
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;
  }
}

Add your plugin after you initialize Ampli.

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

Ampli CLI

Pull

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

bash
ampli pull

Log in to your workspace when prompted, then select a source.

bash
 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

For more information, refer to ampli pull.

Status

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

bash
ampli status [--update]

The output displays status and indicates what events are missing.

bash
 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

For more information, refer to ampli status.

Migrate 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 the Source runtime.

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

  2. Follow the steps on this page 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.

    Amplitude no longer supports Middleware. The new Plugin architecture replaces it. Migrate from Middleware to a Plugin.

Was this helpful?