
The [Ampli Wrapper](/docs/sdks/ampli) 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 provides autocompletion for events and properties defined in Data and enforces your event schemas in code to prevent bad instrumentation.

Amplitude Data supports tracking analytics events from browser apps written in JavaScript (ES6 and higher) and TypeScript (2.1 and higher). Amplitude packages the generated tracking library as a CJS module.

{% callout type="tip" title="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 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 activation, 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 need.
{% /callout %}

{% callout type="tip" title="Linting with Prettier" %}
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`. For more information, refer to the [Prettier documentation](https://prettier.io/docs/en/ignore.html).
{% /callout %}

## Quickstart

1. [(Prerequisite) Create a Tracking Plan in Amplitude Data](/docs/data/create-tracking-plan)

   Plan your events and properties in [Amplitude Data](https://data.amplitude.com/).

1. [Install the Amplitude SDK](#install-the-amplitude-sdk)

   ```bash
   npm install @amplitude/analytics-browser
   ```

1. [Install the Ampli CLI](#install-the-ampli-cli)

   ```bash
   npm install -g @amplitude/ampli
   ```

1. [Pull the Ampli Wrapper into your project](#pull)

   ```bash
   ampli pull [--path ./src/ampli]
   ```

1. [Initialize the Ampli Wrapper](#load)

   ```js
   import { ampli } from "./src/ampli";

   ampli.load({ client: { apiKey: AMPLITUDE_API_KEY } });
   ```

1. [Identify users and set user properties](#identify)

   ```js
   ampli.identify("user-id", {
     userProp: "A trait associated with this user",
   });
   ```

1. [Track events with strongly typed methods and classes](#track)

   ```js
   ampli.songPlayed({ songId: "song-1" });
   ampli.track(new SongPlayed({ songId: "song-2" }));
   ```

1. [Flush events before application exit](#flush)

   ```js
   ampli.flush();
   ```

1. [Verify implementation status with CLI](#status)

   ```shell
   ampli status [--update]
   ```

## Install the Amplitude SDK

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

{% code-group %}
```bash npm
npm install @amplitude/analytics-browser
```

```bash yarn
yarn add @amplitude/analytics-browser
```
{% /code-group %}

{% callout type="note" title="" %}
When you use Ampli in the browser, Amplitude recommends loading `amplitude-js` as a module rather than as a JavaScript snippet.
{% /callout %}

## Install the Ampli CLI

You can install the Ampli CLI from Homebrew or npm.

{% code-group %}
```bash brew
brew tap amplitude/ampli
brew install ampli
```

```bash npm
npm install -g @amplitude/ampli
```
{% /code-group %}

### 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 which provides convenience methods. The Ampli Wrapper also grants access to every method of the underlying Amplitude SDK through `ampli.client`. For [more details, refer to the Ampli documentation](/docs/sdks/ampli#wrapping-the-amplitude-sdk).

### Load

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

| Option | Type | Required | Description |
|---|---|---|---|
| `disabled` | Boolean | No | 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.configuration` | `Amplitude.Config` | No | Overrides the default configuration for the AmplitudeClient. |

Example of initialization with `load` to override the default configuration:

```js
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.

The Ampli Wrapper creates types for user properties as well as for events and their 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.

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

The options argument allows you to pass [Amplitude fields](/docs/apis/analytics/http-v2#event-array-keys) 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 accepts a required `groupType` and `groupName`.

```ts
ampli.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 performs 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 `groupType:groupName` as a user property, overwrites any existing `groupName` value set for that user's `groupType`, and overwrites the corresponding user property value. `groupType` is a string. `groupName` accepts 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', then 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 gets 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 lets you pass [Amplitude fields](/docs/apis/analytics/http-v2#event-array-keys), like `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 has an Amplitude field defined: `deviceId`. For more information, refer to [Amplitude fields](/docs/apis/analytics/http-v2/#event-array-keys).

```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 let you extend Amplitude behavior, for example, by modifying event properties (enrichment type) or sending to third-party APIs (destination type).

First, define your plugin. Enrichment Plugin example:

{% code-group %}
```ts TypeScript
import {
  BrowserConfig,
  EnrichmentPlugin,
  Event,
} from "@amplitude/analytics-types";

export class AddEventIdPlugin implements EnrichmentPlugin {
  name = "add-event-id";
  type = "enrichment" as const;
  currentId = 100;

  /**
   * setup() is called on plugin installation
   * example: client.add(new AddEventIdPlugin());
   */
  setup(config: BrowserConfig): 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;
  }
}
```

```js JavaScript
export class AddEventIdPlugin {
  name = "add-event-id";
  type = "enrichment";
  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;
  }
}
```
{% /code-group %}

Add your plugin after you initialize Ampli.

```ts
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, and 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`](/docs/sdks/ampli/ampli-cli#pull).

### Status

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

```bash
ampli status [--update]
```

The output displays status and indicates which 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`](/docs/sdks/ampli/ampli-cli#status).
