See examples of Ampli implementations for the following languages on GitHub:
Ampli supports 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.
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:
After it's activated, type errors appear directly in the IDE.
Jetbrains provides similar support:
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.
(Prerequisite) Create a Tracking Plan in Amplitude Data
Plan your events and properties in Amplitude Data.
1npm install @amplitude/analytics-node
1npm install -g @amplitude/ampli
Pull the Ampli Wrapper into your project
1ampli pull [--path ./src/ampli]
1import { ampli } from './src/ampli';2 3ampli.load({ client: { apiKey: AMPLITUDE_API_KEY } });
Identify users and set user properties
1ampli.identify('user-id', {2 userProp: 'A trait associated with this user'3});
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' });
Flush events before application exit
1ampli.flush();
Verify implementation status with CLI
1ampli status [--update]
If you haven't already, install the core Amplitude SDK dependencies.
1npm install @amplitude/analytics-node
1yarn add @amplitude/analytics-node
You can install the Ampli CLI from Homebrew or NPM.
1brew tap amplitude/ampli2brew install ampli
1npm install -g @amplitude/ampli
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
Ampli generates a thin facade over the Amplitude SDK which provides convenience methods. The Ampli Wrapper also grants access to every method of the underlying Amplitude SDK through ampli.client
. More details.
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 . |
client.instance |
Required if client.apiKey isn't set. AmplitudeClient . Specifies an Amplitude instance. By default Ampli creates an instance for you. |
client.apiKey |
Required if client.instance isn't set. String . Specifies an API Key. This option overrides the default, which is the API Key configured in your tracking plan. |
client.configuration |
Optional. Amplitude.Config . Overrides the default configuration for the AmplitudeClient. |
See the following for an example of initialization with load
to override the default configuration:
1ampli.load({2 client: {3 apiKey: AMPLITUDE_API_KEY,4 configuration: {5 minIdLength: 10,6 }7 }8});
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.
1ampli.identify('user-id', {2 role: 'admin'3});
The options argument allows you to pass Amplitude fields for this call, such as deviceId
.
1ampli.identify('user-id', {2 role: 'admin'3}, {4 deviceId: 'my-device-id'5});
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.client.setGroup('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 show 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:
1ampli.client.setGroup('orgId', ['10', '20']);
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 structure is like this:
1ampli.eventName(properties: EventNameProperties, options: EventOptions)
The properties
argument passes event properties.
The options
argument allows you to pass Amplitude fields, like price
, quantity
and revenue
.
For example, in the following code, 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.
1ampli.songPlayed({2 songId: 'songId', // string,3 songFavorited: true, // boolean4}, {5 deviceId: 'a-device-id',6});
Ampli also generates a class for each event.
1const myEventObject = new SongPlayed({2 songId: 'songId', // string,3 songFavorited: true, // boolean4});
Track Event objects using Ampli track
:
1ampli.track(new SongPlayed({2 songId: 'songId', // string,3 songFavorited: true, // boolean4}));
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.
This can be useful to call prior to application exit.
1ampli.flush();
Plugins allow you to extend the Amplitude behavior, for example, modifying event properties (enrichment type) or sending to third-party APIs (destination type).
First you need to define your plugin.
1import { Config, EnrichmentPlugin, Event, PluginType } from '"@amplitude/analytics-node"'; 2 3export class AddEventIdPlugin implements EnrichmentPlugin { 4 name = 'add-event-id'; 5 type = PluginType.ENRICHMENT as const; 6 currentId = 100; 7 8 /** 9 * setup() is called on plugin installation10 * example: client.add(new AddEventIdPlugin());11 */12 setup(config: Config): Promise<undefined> {13 this.config = config;14 }15 16 /**17 * execute() is called on each event instrumented18 * example: client.track('New Event');19 */20 execute(event: Event): Promise<Event> {21 event.event_id = this.currentId++;22 return event;23 }24}
1export class AddEventIdPlugin { 2 name = 'add-event-id'; 3 currentId = 100; 4 5 /** 6 * setup() is called on plugin installation 7 * example: client.add(new AddEventIdPlugin()); 8 */ 9 setup(config) {10 this.config = config;11 }12 13 /**14 * execute() is called on each event instrumented15 * example: client.track('New Event');16 */17 execute(event) {18 event.event_id = this.currentId++;19 return event;20 }21}
Add your plugin after init Ampli.
1ampli.client.add(new AddEventIdPlugin())
The pull
command downloads the Ampli Wrapper code to your project. Run the pull
command from the project root.
1ampli pull
Log in to your workspace when prompted and select a source.
1➜ ampli pull2Ampli project is not initialized. No existing `ampli.json` configuration found.3? Create a new Ampli project here? Yes4? Organization: Amplitude5? Workspace: My Workspace6? Source: My Source
Learn more about ampli pull
.
Verify that events are in your code with the status command:
1ampli status [--update]
The output displays status and indicates what events are missing.
1➜ ampli status2✘ Verifying event tracking implementation in source code3 ✔ Song Played (1 location)4 ✘ Song Stopped Called when a user stops playing a song.5Events Tracked: 1 missed, 2 total
Learn more about ampli status
.
@amplitude/node
runtimeMigrate from Ampli for @amplitude/node
to Ampli for @amplitude/analytics-node
by following these steps.
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
.
Follow steps on this page for detailed setup and usage instructions.
Remove legacy dependencies from your project.
yarn remove @amplitude/node
Add new dependencies.
yarn add @amplitude/analytics-node
Pull the latest Ampli Wrapper.
ampli pull
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.
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.