# Amplitude Documentation — Analytics # Generated: 2026-09-08T23:39:56Z # Pages included: 48 of 200 # Source: https://amplitude.com/docs/llms.txt # Product feed: llms-analytics.txt > Digital analytics charts, cohorts, dashboards, analytics SDKs, and HTTP API v2 ingestion. > Token budget (150,000 tokens) reached. Use Docs MCP or `/docs/api/content/` for pages not included here. > For AI agents: a documentation index is available at [/docs/llms.txt](/docs/llms.txt). Append `.md` to any page URL for markdown, or send `Accept: text/markdown`. ================================================================================ # Analytics URL: https://amplitude.com/docs/analytics Updated: 2024-04-16 ================================================================================ # Analytics Amplitude Analytics turns event data into charts, cohorts, and dashboards that answer product questions without SQL. It runs 17 chart types over your behavioral data, groups users into reusable cohorts, and surfaces anomalies as they happen, so product teams find what changed, who it affected, and what to ship next. Use Analytics when you need to quantify behavior across many users: conversion, retention, engagement, cohort comparison. If you need to watch a single user's session unfold to understand why they behaved that way, use [Session Replay](https://amplitude.com/docs/session-replay) instead. **Outcome:** [Answer product questions](https://amplitude.com/docs/analytics/charts/find-the-right-chart) Pick from 17 chart types to investigate funnels, retention, journeys, and more. **Outcome:** [Reuse the segments that matter](https://amplitude.com/docs/analytics/behavioral-cohorts) Save a group of users once, then apply it across charts, experiments, and integrations. **Outcome:** [Keep your team aligned](https://amplitude.com/docs/analytics/dashboard-create) Bring related charts into one dashboard the team can review at a glance. **Outcome:** [Collaborate on findings](https://amplitude.com/docs/analytics/workspace) Group charts, cohorts, and notebooks in shared spaces so the right people can act on them. **Outcome:** [Catch unexpected shifts early](https://amplitude.com/docs/analytics/anomaly-forecast) Surface anomalies automatically and trace each one back to the change that caused it. **Outcome:** [Report on accounts, not just users](https://amplitude.com/docs/analytics/account-level-reporting) Roll usage and revenue up to the company, team, or workspace for B2B analysis. ## Chart types Every analytical question maps to a chart type. Start with [Find the right chart](https://amplitude.com/docs/analytics/charts/find-the-right-chart) if you're not sure where to begin, or jump straight to one of the most-used chart types below. **Outcome:** [Track behavior over time](https://amplitude.com/docs/analytics/charts/event-segmentation/event-segmentation-build) Use Event Segmentation to see how often users trigger an action and break results down by any property. **Outcome:** [Find where users drop off](https://amplitude.com/docs/analytics/charts/funnel-analysis/funnel-analysis-build) Use Funnel Analysis to measure conversion across a sequence of steps and pinpoint the leak. **Outcome:** [Measure who comes back](https://amplitude.com/docs/analytics/charts/retention-analysis/retention-analysis-build) Use Retention Analysis to see how well your product keeps users coming back over days, weeks, or months. **Outcome:** [See the paths users take](https://amplitude.com/docs/analytics/charts/journeys/journeys-understand-paths) Use Journeys to map what users do before and after a key event in your product. **Outcome:** [Spot your power features](https://amplitude.com/docs/analytics/charts/engagement-matrix/engagement-matrix-discover) Use the Engagement Matrix to compare adoption and frequency side by side and find what hooks users. **Outcome:** [Decide which variant won](https://amplitude.com/docs/analytics/charts/experiment-results/experiment-results-dig-deeper) Use Experiment Results to evaluate A/B tests with statistical rigor and shared metric definitions. Go to [all chart types](https://amplitude.com/docs/analytics/charts/find-the-right-chart) to browse the full catalog. ## Cohorts A cohort is a saved group of users who share a behavior or property. Build one once, then reuse it across charts and dashboards to track how a segment performs over time. - [Create a cohort](https://amplitude.com/docs/analytics/create-cohorts) from a chart, a user list, or a property definition. - [Compare cohorts](https://amplitude.com/docs/analytics/compare-cohorts) to measure how two or more segments differ on any metric. - [Track cohort changes](https://amplitude.com/docs/analytics/track-cohort-changes) to watch segments grow or shrink over time. ## Dashboards Dashboards bring multiple charts into one view. Use them to monitor product health, share recurring reports, or run a weekly team review. - [Create a dashboard](https://amplitude.com/docs/analytics/dashboard-create) and add charts from anywhere in your workspace. - [Set dashboard preferences](https://amplitude.com/docs/analytics/dashboard-preferences) for filters, time ranges, and comparisons. - [Subscribe to a dashboard](https://amplitude.com/docs/analytics/dashboard-subscribe) to get scheduled snapshots in email or Slack. ## Share and collaborate Analytics is more useful when your whole team can act on it. Organize work in spaces, capture findings in notebooks, and push charts into the tools your team already uses. - [Collaborate with spaces](https://amplitude.com/docs/analytics/collaborate-with-spaces) to group related charts, cohorts, and dashboards. - [Document findings in notebooks](https://amplitude.com/docs/analytics/notebooks) that blend charts, text, and images. - [Integrate with Slack](https://amplitude.com/docs/analytics/integrate-slack), [Microsoft Teams](https://amplitude.com/docs/analytics/integrate-microsoft-teams), [Discord](https://amplitude.com/docs/analytics/integrate-discord), or [Miro](https://amplitude.com/docs/analytics/integrate-miro) to share charts where conversations happen. - [Share externally](https://amplitude.com/docs/analytics/share-external) with clients or stakeholders who don't have an Amplitude seat. ## Start with common questions Use these workflows when you need a reliable starting point for product analysis. - [Analyze feature adoption](https://amplitude.com/docs/get-started/analyze-feature-adoption) to understand which features users discover and return to. - [Understand conversion rate](https://amplitude.com/docs/get-started/understand-conversion-rate) to measure movement through a key workflow. - [Analyze acquisition channels](https://amplitude.com/docs/get-started/analyze-acquisition-channels) to compare which sources bring valuable users. - [Review user activity](https://amplitude.com/docs/get-started/understand-user-activity) to investigate behavior for a single user or account. ## Keep analysis reusable Turn one-off analysis into shared assets that teams can use repeatedly. - Save important charts to dashboards so teams monitor the same metrics. - Use cohorts to make segments consistent across charts, experiments, and activation workflows. - Add context in notebooks so stakeholders understand the question, method, and outcome. - Organize related work in spaces to keep charts, cohorts, dashboards, and notebooks together. ### [Getting Started with Amplitude Analytics](https://academy.amplitude.com/path/getting-started-with-amplitude-analytics-learning-path) Learn the most fundamental features of Amplitude Analytics, including cohorts. ================================================================================ # Browser SDK 2 URL: https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2 ================================================================================ # Browser SDK 2 - **Package:** `@amplitude/analytics-browser` ([npm](https://www.npmjs.com/package/@amplitude/analytics-browser)) - **Latest version:** 2.45.8 Amplitude's Browser SDK 2 lets you send events to Amplitude. ## Install the SDK Install the dependency with npm, yarn, or the script loader. > **Info:** Unified SDK > > Install the [Browser Unified SDK](https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk) to access the Experiment SDK along with other Amplitude products (Analytics, Session Replay). The Unified SDK provides a single entry point for all Amplitude features and simplifies the integration by initializing and configuring all components for you. #### Script loader When you use the script loader and enable Autocapture, Browser SDK tracks interactions on your site automatically. For more information, refer to [Autocapture](#autocapture-replaces-defaulttracking). #### npm ```bash # Install Analytics SDK only npm install @amplitude/analytics-browser # Or install Unified SDK to get access to all Amplitude products npm install @amplitude/unified ``` Import Amplitude into your project ```js // If using Analytics SDK only import * as amplitude from "@amplitude/analytics-browser"; // If using Unified SDK import * as amplitude from "@amplitude/unified"; ``` #### yarn ```bash # Install Analytics SDK only yarn add @amplitude/analytics-browser # Or install Unified SDK to get access to all Amplitude products yarn add @amplitude/unified ``` Import Amplitude into your project ```js // If using Analytics SDK only import * as amplitude from "@amplitude/analytics-browser"; // If using Unified SDK import * as amplitude from "@amplitude/unified"; ``` ## Initialize the SDK > **Warning:** Load and initialize only when context is ready > > Don't load the Amplitude SDK from third-party scripts that run before the page has fully loaded. In those setups, user identifiers, traits, and page URL or state often aren't available yet, so the SDK may send early events with missing or incorrect properties. Initialize the SDK only after your app has access to all relevant data (for example, user ID, user properties, and the final page URL). > **Note:** Sending events > > This SDK uses the [HTTP V2](https://amplitude.com/docs/apis/analytics/http-v2) API and follows the same constraints for events. Make sure that all events logged in the SDK have the `event_type` field and at least one of `deviceId`  (included by default) or `userId`, and follow the HTTP API's constraints on each of those fields. > > To prevent instrumentation issues, device IDs and user IDs must be strings with a length of 5 characters or more. If an event contains a device ID or user ID that's too short, Amplitude removes the ID value from the event. If the event doesn't have a `userId` or `deviceId` value, Amplitude may reject the upload with a 400 status. Override the default minimum length of 5 characters by setting the `minIdLength` config option. This SDK requires initialization before you can instrument any events and requires your Amplitude project's API key. You can pass an optional `userID` and `config` object in this call. ```js // Option 1, initialize with Amplitude API key only amplitude.init(AMPLITUDE_API_KEY); // Option 2, initialize with options amplitude.init(AMPLITUDE_API_KEY, options); // Option 3, initialize with user ID if it's already known amplitude.init(AMPLITUDE_API_KEY, "user@amplitude.com"); // Option 4, initialize with a user ID and options amplitude.init(AMPLITUDE_API_KEY, "user@amplitude.com", options); ``` > **Warning:** > > When using the SDK in an [Angular](https://angular.dev/) app with [Zone.js](https://angular.dev/api/core/NgZone), invoke `init` [outside of the Angular zone](https://angular.dev/api/core/NgZone#runOutsideAngular). > > ```javascript > runOutsideAngular(function () { > amplitude.init(...args); > }); > ``` > > The Angular zone overwrites certain DOM functions that, when invoked by [Amplitude autocapture](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2#autocapture-replaces-defaulttracking), cause some user interactions to break. > **Info:** Next.js Integration > > For detailed instructions on integrating Amplitude with Next.js applications, including both client-side and server-side setups, refer to the [Next.js Installation Guide](https://amplitude.com/docs/sdks/frameworks/nextjs-installation-guide). ## Configure the SDK #### SDK configuration options | Name | Description | Default Value | | --- | --- | --- | | `instanceName` | `string`. The instance name. | `$default_instance` | | `flushIntervalMillis` | `number`. Sets the interval of uploading events to Amplitude in milliseconds. | 1,000 (1 second) | | `flushQueueSize` | `number`. Sets the maximum number of events batched in a single upload attempt. | 30 events | | `flushMaxRetries` | `number`. Sets the maximum number of retries for failed upload attempts. This is only applicable to errors that the SDK can retry. | 5 times. | | `logLevel` | `LogLevel.None` or `LogLevel.Error` or `LogLevel.Warn` or `LogLevel.Verbose` or `LogLevel.Debug`. Sets the log level. You can also use numeric values: `0` (None), `1` (Error), `2` (Warn), `3` (Verbose), or `4` (Debug). | `LogLevel.Warn` | | `loggerProvider ` | `Logger`. Sets a custom `loggerProvider` class that implements the [Logger interface](https://github.com/amplitude/Amplitude-TypeScript/blob/main/packages/analytics-types/src/logger.ts#L1-L8) to emit log messages to a specified destination. | [Amplitude Logger](https://github.com/amplitude/Amplitude-TypeScript/blob/main/packages/analytics-core/src/logger.ts) | | `minIdLength` | `number`. Sets the minimum length for the value of `userId` and `deviceId` properties. | `5` | | `optOut` | `boolean`. Sets permission to track events. Setting a value of `true` prevents Amplitude from tracking and uploading events. | `false` | | `serverUrl` | `string`. Sets the URL where the SDK uploads events. | `https://api2.amplitude.com/2/httpapi` | | `serverZone` | `EU` or `US`. Sets the Amplitude server zone. Set this to `EU` for Amplitude projects created in `EU` data center. | `US` | | `useBatch` | `boolean`. Sets whether to upload events to Batch API instead of the default HTTP V2 API or not. | `false` | | `appVersion` | `string`. Sets an app version for tracked events. This can be the version of your application. For example: "1.0.0". | `undefined` | | `autocapture` | `boolean|AutocaptureOptions`. Configures autocapture tracking. Refer to [Autocapture](#autocapture-replaces-defaulttracking). | | | `defaultTracking` | `boolean`. Deprecated in version 2.10.0. Use `autocapture` instead. Configures default event tracking. | `true` | | `customEnrichment` | `boolean | CustomEnrichmentOptions`. Whether the SDK adds the [Custom Enrichment plugin](https://amplitude.com/docs/sdks/analytics/browser/custom-enrichment-plugin), which runs an Amplitude-managed enrichment function on every event. Pass `{ enabled: boolean, body: string }` to configure it. Available in version 2.37.0 and later. | `false` | | `deviceId` | `string`. Sets an identifier for the device running your application. | `UUID()` | | `sessionId` | `number`. Sets a custom session ID as a Unix timestamp in milliseconds. | Current timestamp | | `identify` | `Identify`. Calls "identify" with this object during initialization. Called before Autocapture events, like `session_start`, ensuring proper attribution of events. | `undefined` | | `cookieOptions.domain` | `string`. Sets the domain property of cookies created. | `undefined` | | `cookieOptions.expiration` | `number`. Sets expiration of cookies created in days. | 365 days | | `cookieOptions.sameSite` | `string`. Sets `SameSite` property of cookies created. | `Lax` | | `cookieOptions.secure` | `boolean`. Sets `Secure` property of cookies created. | `false` | | `cookieOptions.upgrade` | `boolean`. Sets upgrading from cookies created by [maintenance Browser SDK](https://amplitude.com/docs/sdks/analytics/browser/javascript-sdk). If `true`, new Browser SDK deletes cookies created by maintenance Browser SDK. If `false`, Browser SDK keeps cookies created by maintenance Browser SDK. | `true` | | `identityStorage` | `string`. Sets storage API for user identity. Options include `cookie` for `document.cookie`, `localStorage` for `localStorage`, `sessionStorage` for `sessionStorage`, or `none` to opt-out of persisting user identity. | `cookie` | | `pageCounter` | `number`. Sets the page count for the current session, which the SDK uses for landing-page analysis. | `undefined` | | `partnerId` | `string`. Sets partner ID. Amplitude requires the customer who built an event ingestion integration to add the partner identifier to `partner_id`. | `undefined` | | `sessionTimeout` | `number`. Sets the period of inactivity from the last tracked event before a session expires in milliseconds. | 1,800,000 milliseconds (30 minutes) | | `storageProvider` | `Storage`. Sets a custom implementation of `Storage` to persist unsent events. | `LocalStorage` | | `userId` | `string`. Sets an identifier for the tracked user. Must have a minimum length of 5 characters unless overridden with the `minIdLength` option. | `undefined` | | `trackingOptions` | `TrackingOptions`. Configures tracking of extra properties. | Enable all tracking options by default. | | `transport` | `TransportType | TransportConfig`. Sets the request API to use. Pass a string (`'fetch'`, `'xhr'`, or `'beacon'`), or an object with `type`, `headers`, and `enableKeepalive` properties. Use `headers` to set custom HTTP headers. Go to [Custom HTTP request headers](#custom-http-request-headers). Use `enableKeepalive` to control whether `fetch` requests survive page navigation. Go to [Survive page navigation with keepalive](#survive-page-navigation-with-keepalive). | `'fetch'` | | `enableRequestBodyCompression` | `boolean`. Enables gzip compression for event upload request bodies. When using Amplitude's default ingestion endpoints, the SDK enables compression automatically. When using a custom `serverUrl`, set this to `true` to enable compression. Refer to [Request body compression](#request-body-compression) for more details. | `false` (custom servers), `true` (default endpoints) | | `offline` | `boolean`. Whether the SDK connects to the network. Refer to [Offline mode](#offline-mode). | `false` | | `fetchRemoteConfig` | `boolean`. _Deprecated._ Use `remoteConfig.fetchRemoteConfig` instead. Whether the SDK fetches remote configuration. Refer to [Remote configurations](#remote-configuration). | `true` | | `remoteConfig` | `object`. Remote configuration options. Go to [Remote configuration](#remote-configuration). Fields: `fetchRemoteConfig` (`boolean`, default `true`): whether the SDK fetches remote configuration. `serverUrl` (`string`): custom server URL for proxying remote config requests. | `undefined` | | `networkTrackingOptions` | `NetworkTrackingOptions`. _Deprecated._ Use `autocapture.networkTracking` instead. | `undefined` | | `enableDiagnostics` | `boolean`. Enables SDK diagnostics. | `true` | ### Configure batching behavior To support high-performance environments, the SDK sends events in batches. The SDK queues in memory every event the `track` method logs. Customize this behavior with the `flushQueueSize` and `flushIntervalMillis` configuration parameters. If you plan to send large batches of data at once, set `useBatch` to `true` and `setServerUrl` to the batch API: `https://api2.amplitude.com/batch`. Both standard and batch modes use the same event upload threshold and flush time intervals. ### EU data residency To send data to Amplitude's EU-based servers, set the server zone when you initialize the client. After you set the server zone, the SDK sends to the region determined by this setting. ```ts amplitude.init(AMPLITUDE_API_KEY, { serverZone: "EU", }); ``` > **Note:** Data residency requirement > > To send data to Amplitude's EU servers, your organization must use the EU data storage region, which you set during signup. ### Debugging Control the level of logs the SDK prints to the console with the following `logLevel` settings: | Log level | Description | | --- | --- | | `none` | Suppresses all log messages | | `error` | Shows error messages only | | `warn` | Default. Shows error and warning messages. | | `verbose` | Shows informative messages. | | `debug` | Shows all messages, including function context information for each public method the SDK invokes. Amplitude recommends this log level for development only. | Set the `logLevel` parameter. ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { logLevel: amplitude.Types.LogLevel.Warn, }); ``` > **Note:** Using numeric values for logLevel > > In environments where you can't import the `LogLevel` enum (such as Google Tag Manager), use numeric values instead: > > | Numeric value | Log level | Enum equivalent | > | --- | --- | --- | > | `0` | None | `LogLevel.None` | > | `1` | Error | `LogLevel.Error` | > | `2` | Warn | `LogLevel.Warn` | > | `3` | Verbose | `LogLevel.Verbose` | > | `4` | Debug | `LogLevel.Debug` | > > For example, to suppress all logs in GTM, set `logLevel` to `0`: > > ```js > // In GTM configuration > logLevel: 0; > ``` > > Don't use string values like `"LogLevel.None"` in GTM, as these won't work correctly. The default logger outputs log to the developer console. You can provide your own logger implementation based on the `Logger` interface for any customization purpose. For example, collecting any error messages from the SDK in a production environment. Set the logger by configuring the `loggerProvider` with your own implementation. ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { loggerProvider: new MyLogger(), }); ``` #### Debug mode Enable the debug mode by setting the `logLevel` to "Debug", for example: ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { logLevel: amplitude.Types.LogLevel.Debug, }); ``` With the default logger, the SDK outputs extra function context information to the developer console when you invoke any SDK public method, including: - `type`: Category of this context, for example "invoke public method". - `name`: Name of invoked function, for example "track". - `args`: Arguments of the invoked function. - `stacktrace`: Stacktrace of the invoked function. - `time`: Start and end timestamp of the function invocation. - `states`: Useful internal states snapshot before and after the function invocation. ## Performance The Browser SDK 2 minimizes its impact on page performance through event batching, asynchronous processing, and optimizing bundle sizes. ### Bundle size The Browser SDK 2 bundle size varies based on the installation method and features you use. For the most up-to-date bundle size information, check the [npm package page](https://www.npmjs.com/package/@amplitude/analytics-browser) or [BundlePhobia](https://bundlephobia.com/package/@amplitude/analytics-browser). ### Runtime performance The Browser SDK 2 runs asynchronously and doesn't block the main thread during event tracking. Performance characteristics include: - **Event tracking**: Event tracking operations are non-blocking and typically complete in less than 1ms for each event. - **Network requests**: The SDK batches events and sends them asynchronously, minimizing network overhead. The default configuration batches up to 30 events or sends every 1 second, whichever comes first. - **Memory usage**: The SDK maintains a small in-memory queue for event batching. Memory usage scales with the number of queued events (default: up to 30 events). - **CPU impact**: Event processing and batching operations have minimal CPU impact, typically less than 1% of CPU time during normal operation. ### Optimization tips To further optimize performance: - Adjust `flushQueueSize` and `flushIntervalMillis` to balance between network efficiency and memory usage. - Use the `offline` mode to defer event uploads when network conditions are poor. - Enable `useBatch` mode for high-volume event tracking to reduce the number of HTTP requests. ## Autocapture (replaces defaultTracking) Starting in SDK version 2.10.0, the Browser SDK can autocapture events when you enable it, and adds a configuration to control the collection of autocaptured events. The Browser SDK can autocapture the following event types: - Attribution - Page views - Sessions - Form interactions - File downloads - Element interactions - Page URL enrichment - Network tracking - Web vitals #### Autocapture options | Name | Description | | --- | --- | | `config.autocapture.attribution` | Optional. Type: `boolean`. Enables or disables marketing attribution tracking. If `true`, Amplitude tracks marketing attribution events. Default value is `true`. | | `config.autocapture.pageViews` | Optional. Type: `boolean`. Enables or disables default page view tracking. If `true`, Amplitude tracks page view events on initialization. Tracked event properties include: `[Amplitude] Page Domain`, `[Amplitude] Page Location`, `[Amplitude] Page Path`, `[Amplitude] Page Title`, `[Amplitude] Page URL`. Default value is `true`. Refer to [Track page views](#track-page-views) for more information. | | `config.autocapture.sessions` | Optional. Type: `boolean`. Enables or disables session tracking. If `true`, Amplitude tracks session start and session end events. Otherwise, Amplitude doesn't track session events. When this setting is `false`, Amplitude tracks `sessionId` only. Default value is `true`. Refer to [Track sessions](#track-sessions) for more information. | | `config.autocapture.formInteractions` | Optional. Type: `boolean`. Enables or disables form interaction tracking. If `true`, Amplitude tracks form start and form submit events. Tracked event properties include: `[Amplitude] Form ID`, `[Amplitude] Form Name`, `[Amplitude] Form Destination`. Default value is `true`. Refer to [Track form interactions](#track-form-interactions) for more information. | | `config.autocapture.fileDownloads` | Optional. Type: `boolean`. Enables or disables file download tracking. If `true`, Amplitude tracks file download events. Tracked event properties include: `[Amplitude] File Extension`, `[Amplitude] File Name`, `[Amplitude] Link ID`, `[Amplitude] Link Text`, `[Amplitude] Link URL`. Default value is `true`. Refer to [Track file downloads](#track-file-downloads) for more information. | | `config.autocapture.elementInteractions` | Optional. Type: `boolean`. Enables or disables element interaction tracking. If `true`, Amplitude tracks clicks and form field interactions. Default value is `false`. Go to [Track element interactions](#track-element-interactions) for more information and configuration options. | | `config.autocapture.frustrationInteractions` | Optional. Type: `boolean`. Enables or disables frustration interaction tracking. If `true`, Amplitude tracks rage clicks and dead clicks. Error clicks and thrashed cursor are available separately (minimum SDK version 2.40.0). Default value is `false`. Review [Track frustration interactions](#track-frustration-interactions) for more information and configuration options. Minimum SDK version 2.24.0. | | `config.autocapture.pageUrlEnrichment` | Optional. Type: `boolean`. Enables or disables page URL enrichment tracking. If `true`, Amplitude automatically adds page URL-related properties to all events, including previous page information and page type classification. Default value is `true`. Go to [Page URL enrichment plugin](#page-url-enrichment-plugin) for more information. | | `config.autocapture.networkTracking` | Optional. Type: `boolean`. Enables or disables capturing network request events invoked by [XHR](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) and [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). If `true`, Amplitude tracks failed network requests. To configure what Amplitude captures, set this as a network tracking options object. Default value is `false`. Refer to [Track network interactions](#track-network-requests) for more information and configuration options. | | `config.autocapture.webVitals` | Optional. Type: `boolean`. Enables or disables Core Web Vitals tracking. If `true`, Amplitude automatically captures web performance metrics (INP, LCP, FCP, CLS, TTFB) and sends them as `[Amplitude] Web Vitals` events. Default value is `false`. Refer to [Track web vitals](#track-web-vitals) for more information. Minimum SDK version 2.27.0. | ### Remote configuration Autocapture supports [remote configuration](#remote-configuration). For more information, refer to [Autocapture Settings](https://amplitude.com/docs/data/amplitude-data-settings#autocapture). ### Disable Autocapture To disable Autocapture, refer to the following code sample. ```ts // Disable individual default tracked events amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { attribution: false, pageViews: false, sessions: false, formInteractions: false, fileDownloads: false, elementInteractions: false, pageUrlEnrichment: false, webVitals: false, }, }); // Disable all default tracked events amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: false, }); ``` ### Track marketing attribution Amplitude tracks marketing attribution by default. Browser SDK 2 captures UTM parameters, referrer information, and click IDs. As of Browser SDK version 2.45.0, both attribution persistence methods are on by default: - **User property tracking**: Tracks campaign parameters as user properties through identify events. First-touch attribution is tracked only with user properties. User properties can also track the most recent touch. - **Event property tracking**: Attaches campaign parameters to each event's properties for multi-touch attribution. Although you can use user properties for multi-touch attribution, Amplitude recommends event properties because they preserve the attribution context for each event. Use them with [Persisted Properties](https://amplitude.com/docs/data/persisted-properties) to select different attribution models. Both methods work with no configuration change. #### Attribution overview Amplitude tracks marketing attribution to identify your user's traffic source using the UTM, referrer, and click ID parameters. #### UTM parameters UTM (Urchin Traffic Monitor) parameters help you analyze the effectiveness of different ad campaigns and referring sites. UTM parameters are case-sensitive, so Amplitude treats them as different values when the capitalization varies. There are six different UTM parameters evaluated: | Name | Description | | --- | --- | | `utm_source` | This identifies which website sent the traffic (for example, Google, Facebook) | | `utm_medium` | This identifies a specific campaign used (for example, "summer\_sale") | | `utm_campaign` | This identifies a specific campaign used (for example, "summer\_sale") | | `utm_term` | This identifies paid search terms used (for example, product+analytics) | | `utm_content` | This identifies what brought the user to the site. Commonly used for A/B testing (for example, "banner-link", "text-link") | | `utm_id` | This identifies the unique campaign ID used to tie a campaign together across platforms and reconcile cost/performance data | Here is an example URL with UTM parameters: ```bash https://www.amplitude.com/?utm_source=newsletter&utm_campaign=product_analytics_playbook&utm_medium=email&utm_term=product%20analytics&utm_content=banner-link ``` #### Referrer parameters Referrer is the URL of the page that linked to the destination page. Amplitude tracks the following parameters: | Name | Description | | --- | --- | | `referrer` | The last page the user was on (for example, `https://amplitude.com/behavioral-analytics-platform?ref=nav`) | | `referring_domain` | The domain that the user was last on (for example, `https://amplitude.com`) | Referrer is an empty string (`''`) if the user navigated to the destination page directly. #### Click ID parameters Click IDs are campaign identifiers included as URL query parameters. Ad platforms use these IDs to identify the campaign and other attributes. While Amplitude doesn't have access to further campaign attributes associated to Click IDs, Amplitude can track Click ID values specified in the following table. | Name | Description | | --- | --- | | `dclid` | Google Marketing Platform click identifier | | `fbclid` | Facebook click identifier | | `gbraid` | Google click identifier on iOS for web-to-app measurement | | `wbraid` | Google click identifier on iOS for app-to-web measurement | | `gclid` | Google click identifier | | `ko_click_id` | Kochava click identifier | | `li_fat_id` | LinkedIn click identifier | | `msclkid` | Microsoft click identifier | | `rdt_cid` | Reddit click identifier | | `ttclid` | TikTok click identifier | | `twclid` | Twitter click identifier | #### First-touch attribution First-touch attribution is available only through user properties. When using user property tracking (default), Amplitude captures the initial attribution data at the start of the first session. Amplitude sets the first-touch attribution values when it sees a user's attribution data for the first time. Amplitude sets the following user properties one time: - `initial_utm_source` - `initial_utm_medium` - `initial_utm_campaign` - `initial_utm_term` - `initial_utm_content` - `initial_utm_id` - `initial_referrer` - `initial_referring_domain` - `initial_gclid` - `initial_fbclid` - `initial_dclid` - `initial_gbraid` - `initial_ko_click_id` - `initial_msclkid` - `initial_ttclid` - `initial_twclid` - `initial_wbraid` - `initial_li_fat_id` - `initial_rdt_cid` #### Multi-touch attribution Multi-touch attribution can use user properties or event properties. Amplitude recommends event properties because they preserve the campaign associated with each event and support attribution modeling with [Persisted Properties](https://amplitude.com/docs/data/persisted-properties). User property tracking captures the most recent attribution data and sets those values on the user identity. For organic or direct traffic, these properties may not be available, so Amplitude unsets them from the user identity when it tracks a new campaign. For every new campaign, Amplitude captures the changes regardless of the state of the user session. You can configure `resetSessionOnNewCampaign` to `true` to reset the session on every new campaign. The default behavior doesn't reset the session on new campaign. Amplitude tracks the following as user properties: - `utm_source` - `utm_medium` - `utm_campaign` - `utm_term` - `utm_content` - `utm_id` - `referrer` - `referring_domain` - `gclid` - `fbclid` - `dclid` - `gbraid` - `ko_click_id` - `msclkid` - `ttclid` - `twclid` - `wbraid` - `li_fat_id` - `rdt_cid` Set `config.autocapture.attribution` to `false` to disable marketing attribution tracking. ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { attribution: false, }, }); ``` #### Advanced configuration for marketing attribution tracking #### Marketing attribution configuration | Name | Description | | --- | --- | | `config.autocapture.attribution.trackingMethod` | Optional. Type: `'userProperty'` or `'eventProperty'` or `['userProperty', 'eventProperty']`. Configures how the SDK persists campaign attribution data. Set to `'userProperty'` to track as user properties only, `'eventProperty'` to attach campaign parameters to event properties only, or `['userProperty', 'eventProperty']` to use both. The default value is `['userProperty', 'eventProperty']` as of version 2.45.0. | | `config.autocapture.attribution.fallbackAttributionEvent` | Optional. Type: `boolean`. When `trackingMethod` includes `'eventProperty'`, fires an `[Amplitude] Attribution` event on each page view and SPA navigation as a fallback when the SDK doesn't track other events. This ensures Amplitude captures campaign data even if users don't trigger other events. Applies only to event property tracking. The default value is `false`. | | `config.autocapture.attribution.excludeReferrers` | Optional. Type: Array of `string` or `RegExp`. Sets rules to decide which referrers to exclude from tracking as traffic source. Use string values for exact matching and RegExp values for pattern matching against the referring domain. When you don't set this option, the SDK excludes the current domain (and its subdomains). If explicitly adding an external referrer to exclude, you must also add the current domain (and its subdomains) as more referrers to exclude. For user property based attribution tracking. | | `config.autocapture.attribution.excludeInternalReferrers` | Optional. Type: `boolean` or `{ condition: 'always' | 'ifEmptyCampaign' }`. When enabled, the SDK doesn't track campaign information when the referrer and the current page are on the same domain (internal referrer). Set to `true` or `{ condition: 'always' }` to always skip campaign tracking for internal referrers. Set to `{ condition: 'ifEmptyCampaign' }` to always skip campaign tracking for internal referrers where there are no UTM parameters or click IDs (empty campaign). For user property based attribution tracking. | | `config.autocapture.attribution.initialEmptyValue` | Optional. Type: `string`. Sets the value to represent undefined/no initial campaign parameter for first-touch attribution. The default value is `"EMPTY"`. For user property based attribution tracking. | | `config.autocapture.attribution.resetSessionOnNewCampaign` | Optional. Type: `boolean`. Configures Amplitude to start a new session if any campaign parameter changes. The default value is `false`. For user property based attribution tracking. | #### Event property tracking As of Browser SDK version 2.45.0, event property tracking is on by default. The SDK attaches campaign parameters (UTMs, click IDs, referrer, and referring\_domain) to the `event_properties` of every tracked event. With event property tracking, the SDK: - Parses campaign parameters on page load and SPA navigations (History API changes like `pushState`, `replaceState`, `popstate`). - Attaches campaign fields to the `event_properties` of every tracked event. User property tracking also remains on by default. Both methods run independently: event property tracking doesn't replace the identify calls that set user properties. To disable event property tracking and use only user property tracking, set `trackingMethod` to `'userProperty'`: ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { attribution: { trackingMethod: "userProperty", }, }, }); ``` To disable user property tracking and use only event property tracking, set `trackingMethod` to `'eventProperty'`: ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { attribution: { trackingMethod: "eventProperty", }, }, }); ``` > **Note:** SDK versions below 2.45.0 > > On Browser SDK versions before 2.45.0, event property tracking is opt-in. To enable it, set `trackingMethod` to `['userProperty', 'eventProperty']`. Event property tracking requires Browser SDK version 2.40.0 or later. > > ```ts > amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { > autocapture: { > attribution: { > trackingMethod: ["userProperty", "eventProperty"], > }, > }, > }); > ``` ##### Fallback attribution event When using event property tracking, enable `fallbackAttributionEvent` to ensure Amplitude captures campaign data even when users don't trigger other events. This sends an `[Amplitude] Attribution` event on each page view and SPA navigation. ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { attribution: { fallbackAttributionEvent: true, }, }, }); ``` ##### Exclude internal referrers Use `excludeInternalReferrers` when you want to avoid attributing traffic to internal navigation (same domain or subdomain). The SDK treats a referrer as internal when `document.referrer` and `location.hostname` resolve to the same domain. - **Always exclude**: Set `excludeInternalReferrers: true` or `excludeInternalReferrers: { condition: 'always' }` to never track campaign information for internal referrers. - **Exclude only when campaign is empty**: Set `excludeInternalReferrers: { condition: 'ifEmptyCampaign' }` to skip campaign tracking for internal referrers where there are no UTM parameters or click IDs. If the user arrives from an internal page with UTM or click IDs, Amplitude still tracks campaign data (if `excludeReferrers` doesn't exclude the referrer). #### Example: always exclude internal referrers ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { attribution: { excludeInternalReferrers: true, }, }, }); ``` #### Example: exclude internal referrers only when campaign is empty ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { attribution: { excludeInternalReferrers: { condition: "ifEmptyCampaign" }, }, }, }); ``` ##### Exclude referrers > **Note:** > > All sub-configurations of `config.autocapture.attribution` take effect only on user properties and do **NOT** affect the event properties of the default page view events. The default value of `config.autocapture.attribution.excludeReferrers` is the top level domain with cookie storage enabled. For example, if you initialize the SDK on `https://www.docs.developers.amplitude.com/`, the SDK first checks `amplitude.com`. If `amplitude.com` doesn't allow cookie storage, then the SDK checks `developers.amplitude.com` and subsequent subdomains. If the domain allows cookie storage, then the SDK sets `excludeReferrers` to a RegExp object `/amplitude\.com$/` which matches and excludes tracking referrers from all subdomains of `amplitude.com`, for example, `data.amplitude.com` and `analytics.amplitude.com`. In addition to excluding referrers from the default configuration, you can add other domains by setting the custom `excludeReferrers`. Custom `excludeReferrers` overrides the default values. For example, to also exclude referrers from `google.com`, set `excludeReferrers` to `[/amplitude\.com$/, 'google.com']`. #### Example of including all referrers Track complete web attribution, including self-referrals, for comprehensive insight: ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { attribution: { // Override the default setting to exclude all subdomains excludeReferrers: [], }, }, }); ``` #### Example of excluding all self-referrals and other subdomains For customers who want to exclude tracking campaign from any referrers across all subdomains of `your-domain.com`, as well as from a specific subdomain: ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { attribution: { excludeReferrers: [/your-domain\.com$/, "www.test.com"], }, }, }); ``` #### Exclude referrers that match a specific pattern For customers who want to exclude tracking campaign from all referrers across all subdomains of `test.com`: ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { attribution: { excludeReferrers: [/test\.com$/], }, }, }); ``` ### Track page views Amplitude tracks page view events by default. The default behavior sends a page view event on initialization. The event type for this event is `[Amplitude] Page Viewed`. Set `config.autocapture.pageViews` to `false` to disable page view tracking. ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { pageViews: false, }, }); ``` #### Advanced configuration for tracking page views Use the advanced configuration to control when the SDK sends page view events. #### Tracking page views options | Name | Description | | --- | --- | | `config.autocapture.pageViews.trackOn` | Optional. Type: `"attribution"` or `() => boolean`. Provides advanced control for when the SDK tracks page view events. Omit or set the value to `undefined`, and configure the SDK to track page view events to on initialization. Set the value to `"attribution"` and configure the SDK to track page view events to only when it tracks web attribution. Set the value to a function that returns a boolean (`true` or `false`) and configure the SDK to track page view events to based on your criteria. | | `config.autocapture.pageViews.trackHistoryChanges` | Optional. Type: `"pathOnly"` or `"all"`. Provides advanced control for single page application for when the SDK tracks page views. Omit or set the value to `"all"`, and configure the SDK to track page view events on any navigation change to the URL within your single page application. For example: navigating from `https://amplitude.com/#company` to `https://amplitude.com/#blog`. Set the value to `pathOnly`, and configure the SDK to track page view events on navigation change to the URL path only within your single page application. For example: navigating from `https://amplitude.com/company` to `https://amplitude.com/blog`. | | `config.autocapture.pageViews.eventType` | Optional. Type: `string`. Customize the event\_type for page view event. | For example, you can configure Amplitude to track page views only when the URL path contains a certain substring. ```ts amplitude.init(API_KEY, OPTIONAL_USER_ID, { autocapture: { pageViews: { trackOn: () => { return window.location.pathname.includes("home"); }, }, }, }); ``` The Browser SDK tracks the following information in page view events. | Name | Description | Default Value | | --- | --- | --- | | `event_type` | `string`. The event type for page view event. Configurable through `autocapture.pageViews.eventType` or enrichment plugin. | `[Amplitude] Page Viewed` from version 1.9.1. | | `event_properties.[Amplitude] Page Domain` | `string`. The page domain. | `location.hostname`or `''`. | | `event_properties.[Amplitude] Page Location` | `string`. The page location. | `location.href` or `''`. | | `event_properties.[Amplitude] Page Path` | `string`. The page path. | `location.path` or `''`. | | `event_properties.[Amplitude] Page Title` | `string`. The page title. | `document.title` or `''`. | | `event_properties.[Amplitude] Page URL` | `string`. The value of page URL. | `location.href.split('?')[0]` or `''`. | | `event_properties.${CampaignParam}` | `string`. The value of `UTMParameters` `ReferrerParameters` `ClickIdParameters` if has any. | Any undefined `campaignParam` or `undefined`. | | `event_properties.[Amplitude] Page Counter` | `integer`. The count of pages viewed in the session. | `1` | | `event_properties.referrer` | `string`. The full URL of the users previous page. | `https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2` | | `event_properties.referring_domain` | `string`. The domain of the page referrer. `amplitude.com` | | Review [this example](https://github.com/amplitude/Amplitude-TypeScript/blob/main/examples/plugins/page-view-tracking-enrichment/index.ts) to understand how to enrich default page view events, such as adding more properties along with page view tracking. > **Warning:** > > If you want Autocapture to include page views for multi-step forms that dynamically update and, therefore, don't refresh the URL with each step, you must use hash elements for Single Page Applications (SPAs). Autocapture doesn't capture the individual dynamic components automatically. Tools such as Google Tag Manager (GTM) can help you [apply hashes to the URL](https://support.google.com/tagmanager/answer/7679410?hl=en) of the SPA between steps. Autocapture can then ingest the different steps as users proceed through the form. #### Page title masking Amplitude lets you to mask page titles in events that include the `[Amplitude] Page Title` property. This protects your sensitive page title information. Use the `data-amp-mask` attribute on your `` element to exclude the actual page title from this property. When the `<title>` element has the `data-amp-mask` attribute, Amplitude replaces the page title with a masked value across all events that capture page title information. For example: ```html <head> <!-- This page title will be masked in all events that capture page titles --> <title data-amp-mask>John Doe - Personal Banking Dashboard ``` ```html Sensitive Customer Information ``` > **Note:** Page title masking behavior > > - Any presence of `data-amp-mask` triggers masking, regardless of the attribute value. > - Amplitude masks only the page title text. The SDK tracks events as expected. > - This affects page view events, page URL enrichment events, and any other events that include `[Amplitude] Page Title`. > - This is separate from [element interaction masking](https://amplitude.com/docs/data/autocapture#precise-text-masking), which uses `data-amp-mask` on individual elements. > - The masked value appears as `*****` in your event data. ### Track sessions Amplitude tracks session events by default. A session is the period of time a user has your website open. For more information, refer to [How Amplitude defines sessions](https://amplitude.com/docs/data/sources/instrument-track-sessions). When a new session starts, Amplitude tracks a session start event, which is the first event of the session. The event type for session start is `[Amplitude] Start Session`. When an existing session ends, Amplitude tracks a session end event, which is the last event of the session. The event type for session end is `[Amplitude] End Session`. You can opt out of tracking session events by setting `config.autocapture.sessions` to `false`. Refer to the following code sample. ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { sessions: false, }, }); ``` ### Track form interactions Amplitude tracks form interaction events by default. The SDK tracks `[Amplitude] Form Started` when the user initially interacts with the form element. An initial interaction can be the first change to a text input, radio button, or dropdown. The SDK tracks a `[Amplitude] Form Submitted` when the user submits the form. If a user submits a form with no initial change to any form fields, Amplitude tracks both `[Amplitude] Form Started` and `[Amplitude] Form Submitted` events. Amplitude can track forms constructed with `
` tags and `` tags nested. For example: ```html
``` #### Disable form interaction tracking Set `config.autocapture.formInteractions` to `false` to disable form interaction tracking. ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { formInteractions: false, }, }); ``` #### Control form submit tracking > **Note:** Minimum SDK version > > Minimum SDK version 2.34.0. You can control when Amplitude tracks `[Amplitude] Form Submitted` events by passing a `FormInteractionsOptions` object with a `shouldTrackSubmit` callback. By default, Amplitude tracks all form submit events. However, when a form has the [`novalidate`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/noValidate) attribute set, the browser [submit event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event) fires without performing default validation checks. This means the submit event triggers even if the form is empty or contains invalid data. In these cases, use `shouldTrackSubmit` to implement custom validation logic and control when Amplitude tracks the submit event. The `shouldTrackSubmit` callback receives the form submit event and returns `true` to track the submit event or `false` to skip tracking. ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { formInteractions: { shouldTrackSubmit: (event) => { // Only track submit if form is valid const form = event.target; return form.checkValidity(); }, }, }, }); ``` ### Track file downloads Amplitude tracks file download events by default. The SDK tracks `[Amplitude] File Downloaded` when the user clicks an anchor or `` tag linked to a file. Amplitude determines that the anchor or `` tag linked to a file if the file extension matches the following regex: `pdf|xlsx?|docx?|txt|rtf|csv|exe|key|pp(s|t|tx)|7z|pkg|rar|gz|zip|avi|mov|mp4|mpe?g|wmv|midi?|mp3|wav|wma` Set `config.autocapture.fileDownloads` to `false` to disable file download tracking. ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { fileDownloads: false, }, }); ``` ### Track element interactions You can enable element interaction tracking to capture clicks and changes for elements on your page, which [Visual labeling](https://amplitude.com/docs/data/visual-labeling) requires and which powers [Zoning Insights](https://amplitude.com/docs/zoning-insights) for analyzing engagement within defined page areas. Refer to [Autocapture privacy and security](https://amplitude.com/docs/data/autocapture#privacy-and-security) for more information about the data collected with these events. Set `config.autocapture.elementInteractions` to `true` to enable element click and change tracking. ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { elementInteractions: true, }, }); ``` #### Advanced configuration for element interactions Use the advanced configuration to control element interaction tracking. #### Tracking element interaction options | Name | Description | | --- | --- | | `config.autocapture.elementInteractions.cssSelectorAllowlist` | Optional. Type: `(string)[]`. Accepts one or more CSS selectors that define which elements on the page Amplitude always tracks. The default value is `['a','button','input','select','textarea','label','video','audio','[contenteditable="true" i]','[data-amp-default-track]','.amp-default-track']`. | | `config.autocapture.elementInteractions.actionClickAllowlist` | Optional. Type: `(string)[]`. Accepts one or more CSS selectors that define which elements on the page Amplitude tracks when the page changes (for example, a new visual element appears) or the click takes a user to a new page. The default value is `['div', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']`. | | `config.autocapture.elementInteractions.pageUrlAllowlist` | Optional. Type: `(string|RegExp)[]`. Defines the URL, URLs, or URL pattern on which Amplitude tracks element click and change events. By default, Amplitude captures element interactions on any URL if undefined. | | `config.autocapture.elementInteractions.dataAttributePrefix` | Optional. Type: `(string|RegExp)[]`. Allows the SDK to capture data attributes as an event property. The default value is `data-amp-track`. | For example, you could configure Amplitude only to capture clicks on elements with a class of `amp-tracking` on the blog pages of a site as follows: ```ts amplitude.init(API_KEY, OPTIONAL_USER_ID, { autocapture: { elementInteractions: { cssSelectorAllowlist: [".amp-tracking"], // When you use `cssSelectorAllowlist` to target specific elements, set `actionClickAllowlist` // to ensure that Amplitude tracks interactions with non-standard clickable elements during page transitions or DOM updates. actionClickAllowlist: [], pageUrlAllowlist: [new RegExp("https://amplitude.com/blog/*")], }, }, }); ``` By default, if you don't use these settings, Amplitude tracks the default selectors on every page where you enable the plugin. > **Note:** > > When you specify the CSS selectors to track, your selection overrides the default. To retain the default selectors, import the `DEFAULT_CSS_SELECTOR_ALLOWLIST` and include it in your code. > > ```js > import { DEFAULT_CSS_SELECTOR_ALLOWLIST } from "@amplitude/plugin-autocapture-browser"; > > const selectors = [ > ...DEFAULT_CSS_SELECTOR_ALLOWLIST, > ".class-of-a-thing-i-want-to-track", > ]; > ``` #### Element interaction events When you enable element interactions for Autocapture, Amplitude sends two events, from which you can create labeled events with [visual labeling](https://amplitude.com/docs/data/visual-labeling): - `[Amplitude] Element Clicked` - `[Amplitude] Element Changed` These two events capture properties that describe the corresponding element and other context about the user's browser: - `[Amplitude] Element ID` - `[Amplitude] Element Class` - `[Amplitude] Element Tag` - `[Amplitude] Element Text` (Collected for `[Amplitude] Element Clicked`, only) - `[Amplitude] Element Href` (Collected for `[Amplitude] Element Clicked`, only) - `[Amplitude] Element Position Left` - `[Amplitude] Element Position Top` - `[Amplitude] Viewport Height` - `[Amplitude] Viewport Width` - `[Amplitude] Page URL` - `[Amplitude] Page Title` - `[Amplitude] Element Selector` - `[Amplitude] Element Hierarchy` - `[Amplitude] Element Attributes` - `[Amplitude] Element Aria Label` - `[Amplitude] Element Parent Label` ### Track frustration interactions Enable frustration interaction tracking to capture rage clicks, dead clicks, error clicks, and thrashed cursor. Amplitude defines these events as: - **Rage click**: A user clicks the same element, within 50px, four times in under a second. - **Dead click**: A user clicks an interactable element, but no navigation change happens and the DOM doesn't change. - **Error click**: A user clicks an element and a browser error occurs within two seconds of the click. - **Thrashed cursor**: A user's cursor moves rapidly back and forth within a short time window, indicating potential frustration. Set `config.autocapture.frustrationInteractions` to `true` to enable capture of dead clicks and rage clicks. Set `config.autocapture.frustrationInteractions.rageClicks` to `true` to enable capture of rage clicks. Set `config.autocapture.frustrationInteractions.deadClicks` to `true` to enable capture of dead clicks. Set `config.autocapture.frustrationInteractions.errorClicks` to `true` to enable capture of error clicks. Set `config.autocapture.frustrationInteractions.thrashedCursor` to `true` to enable capture of thrashed cursors. ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { frustrationInteractions: true, }, }); ``` #### Advanced configuration for frustration interactions Use the advanced configuration to control frustration interaction tracking. #### Tracking frustration interaction options | Name | Description | | --- | --- | | `config.autocapture.frustrationInteractions.deadClicks.cssSelectorAllowlist` | Optional. Type: `(string)[]`. Accepts one or more CSS selectors that define the elements on which Amplitude captures dead clicks. The default value is [DEFAULT\_DEAD\_CLICK\_ALLOWLIST](https://github.com/amplitude/Amplitude-TypeScript/blob/main/packages/analytics-core/src/types/frustration-interactions.ts). | | `config.autocapture.frustrationInteractions.rageClicks.cssSelectorAllowlist` | Optional. Type: `(string)[]`. Accepts one or more CSS selectors that define the elements on which Amplitude captures rage clicks. By default, the SDK captures on any element. | | `config.autocapture.frustrationInteractions.errorClicks.cssSelectorAllowlist` | Optional. Type: `(string)[]`. Accepts one or more CSS selectors that define the elements on which Amplitude captures error clicks. The default value is [DEFAULT\_ERROR\_CLICK\_ALLOWLIST](https://github.com/amplitude/Amplitude-TypeScript/blob/main/packages/analytics-core/src/types/frustration-interactions.ts#L129). | | `config.autocapture.frustrationInteractions.thrashedCursor.directionChanges` | Optional. Type: `number`. Number of direction changes required to consider a thrashed cursor. X-axis changes and Y-axis changes are counted separately. Default is 10 | | `config.autocapture.frustrationInteractions.thrashedCursor.threshold` | Optional. Type: `number`. Time window (in milliseconds) that direction changes need to happen for it to be considered a thrashed cursor. Default is 2000 (2 seconds). | #### Track error clicks > **Note:** Minimum SDK version > > Error clicks and thrashed cursor require Browser SDK version 2.40.0 or later. Error click tracking captures when a user clicks an element and a browser error occurs within two seconds of the click. This helps you identify which user interactions may be triggering errors in your application. Enable error click tracking: ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { frustrationInteractions: { errorClicks: true, }, }, }); ``` When you enable error click tracking, it emits an event `[Amplitude] Error Click` that includes these properties: - `[Amplitude] Kind`: The type of error (one of uncaught exception, console error, unhandled promise rejection). - `[Amplitude] Message`: The error message. - `[Amplitude] Stack`: The error stack trace. - `[Amplitude] Filename`: The filename where the error occurred. - `[Amplitude] Line Number`: The line number where the error occurred. - `[Amplitude] Column Number`: The column number where the error occurred. - Element properties from the clicked element (for example, `[Amplitude] Element Text`, `[Amplitude] Element Tag Name`). #### Track thrashed cursor Thrashed cursor tracking captures when a user's cursor moves rapidly back and forth with multiple direction changes within a short time window. This helps identify areas where users may be experiencing frustration or confusion. Enable thrashed cursor tracking: ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { frustrationInteractions: { thrashedCursor: true, }, }, }); ``` It emits an event called `[Amplitude] Thrashed Cursor`. ### Track network requests Track when network requests fail (only XHR and fetch). By default, tracks network requests with a response code in the range `500-599`, excluding requests made to any `amplitude.com` domain. Set `config.autocapture.networkTracking` to `true` to enable network request tracking. ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { networkTracking: true, }, }); ``` When you enable this setting, Amplitude tracks the `[Amplitude] Network Request` event whenever the application makes a network request. #### Event Properties Descriptions | Event property | Description | | --- | --- | | `[Amplitude] URL` | The URL of the network request with sensitive information masked. | | `[Amplitude] URL Query` | The query parameters of the URL. | | `[Amplitude] URL Fragment` | The fragment identifier of the URL. | | `[Amplitude] Request Method` | The HTTP method used for the request (GET, POST, and so forth). | | `[Amplitude] Status Code` | The HTTP status code of the response. | | `[Amplitude] Error Code` | The local error code if the request failed with out a status code. | | `[Amplitude] Error Message` | The local error message if the request failed with out a status code. | | `[Amplitude] Start Time` | The timestamp when the request started, in milliseconds since Unix epoch. | | `[Amplitude] Completion Time` | The timestamp when the request completed, in milliseconds since Unix epoch. | | `[Amplitude] Duration` | The duration of the request in milliseconds. | | `[Amplitude] Request Body Size` | The size of the request body in bytes. | | `[Amplitude] Response Body Size` | The size of the response body in bytes. | | `[Amplitude] Request Body` | The captured JSON request body (when you configure a `requestBody` capture rule). | | `[Amplitude] Response Body` | The captured JSON response body (when you configure a `responseBody` capture rule). | #### Advanced configuration for network tracking Set `config.autocapture.networkTracking` to a `NetworkTrackingOptions` object to configure which network requests get tracked. ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { networkTracking: { captureRules: [ { statusCodeRange: "400-599", }, ], ignoreHosts: ["*.example.com"], ignoreAmplitudeRequests: true, }, }, }); ``` This example tracks network requests with status codes from 400-599, ignores requests to `*.example.com` domains, and excludes Amplitude's own requests. Review the configuration options below for more details. #### NetworkTrackingOptions | Name | Description | Value | | --- | --- | --- | | `captureRules` | The rules for capturing network requests. You should always append rules with specific hosts to the bottom of the list. | `undefined` | | `ignoreHosts` | The hosts to ignore. Supports wildcard characters `*`. For example, `["*"]` to ignore all hosts, `["*.notmyapi.com", "notmyapi.com"]` to ignore `notmyapi.com` and all subdomains. | `[]` | | `ignoreAmplitudeRequests` | Whether to ignore Amplitude requests. | `true` | #### NetworkTrackingOptions.NetworkCaptureRule | Name | Description | Default Value | | --- | --- | --- | | `urls` | Defines the URL, URLs, or URL pattern to capture. By default captures all URLs. eg. `[/https:\/\/example.com\/api\/*/, 'https://example.com/api/status']` | `` | | `hosts` | The hosts to capture. Supports wildcard characters `*`. eg. `["*"]` to match all hosts, `["*.example.com", "example.com"]` to match `example.com` and all subdomains. (this is deprecated. URLs is the preferred way to filter by hosts.) | `none` | | `methods` | The HTTP methods to capture. e.g.: `["POST", "PUT", "DELETE"]` | `['*']` | | `statusCodeRange` | The status code range to capture. Supports comma-separated ranges or single status codes. For example, `"0,200-299,413,500-599"` | `"500-599"` | | `requestBody` | Captures fields in the request body (go to #BodyCaptureRule). | `undefined` | | `responseBody` | Captures fields in the response body (go to #BodyCaptureRule). | `undefined` | | `requestHeaders` | Captures request headers. If `true`, captures safe headers. If `false`, no headers captured. If an array of strings, captures the specified headers. | `false` | | `responseHeaders` | Captures response headers. If `true`, captures safe headers. If `false`, no headers captured. If an array of strings, captures the specified headers. | `false` | #### BodyCaptureRule | Name | Description | Default Value | | --- | --- | --- | | `allowlist` | Array of JSON property names to capture from request/response bodies. Uses JSON Pointer syntax where leading `/` is optional. Supports wildcards: `*` matches any key, `**` matches any number of keys. Maintains the structure of the original JSON. | `[]` | | `blocklist` | Array of JSON property names to exclude from captured request/response bodies. This removes properties that the allowlist would otherwise capture. | `[]` | #### Safe headers When you set `requestHeaders: true` or `responseHeaders: true`, Amplitude captures only safe headers and excludes sensitive ones that may contain authentication credentials or personally identifiable information. #### Safe headers list - `access-control-allow-origin` - `access-control-allow-credentials` - `access-control-expose-headers` - `access-control-max-age` - `access-control-allow-methods` - `access-control-allow-headers` - `accept-patch` - `accept-ranges` - `age` - `allow` - `alt-svc` - `cache-control` - `connection` - `content-disposition` - `content-encoding` - `content-language` - `content-length` - `content-location` - `content-md5` - `content-range` - `content-type` - `date` - `delta-base` - `etag` - `expires` - `im` - `last-modified` - `link` - `location` - `permanent` - `p3p` - `pragma` - `proxy-authenticate` - `public-key-pins` - `retry-after` - `server` - `status` - `strict-transport-security` - `trailer` - `transfer-encoding` - `tk` - `upgrade` - `vary` - `via` - `warning` - `www-authenticate` - `x-b3-traceid` - `x-frame-options` #### Network body capture If a network request or response body is in JSON, you can capture part of the response body by configuring `responseBody.allowlist` and `responseBody.blocklist`. You can capture part of the request body by configuring `requestBody.allowlist` and `requestBody.blocklist`. The allowlist and blocklist are lists of JSON Pointer-like strings that capture specific fields. (For example: `['foo/bar', 'hello/**']`). `allowlist` tells the client which fields to capture. `excludelist` tells the client to exclude fields from capture (by default, the SDK captures nothing). Example request/response body ```json { "a": "A", "b": { "c": "C", "d": { "e": "E", "f": "F" } }, "g": "G" } ``` | allowlist | Captured Result | | --- | --- | | `a` | `{ "a": "A" }` | | `a/b/*` | `{ "a": { "b": { "c": "C" } } }` | | `b/c` | `{ "b": { "c": "C" } }` | | `b/**` | `{ "b": { "c": "C", "d": { "e": "E", "f": "F" } } }` | | `b/d/*` | `{ "b": { "d": { "e": "E", "f": "F" } } }` | | `b/**` | `{ "b": { "c": "C", "d": { "e": "E", "f": "F" } }` | | `*` | `{ "a": "A", "g": "G" }` | ### Track web vitals Track Core Web Vitals performance metrics automatically. When you enable this, Amplitude captures web performance metrics and sends them as `[Amplitude] Web Vitals` events when the browser tab first becomes hidden (when users navigate away, close the tab, or switch tabs). > **Note:** > > Requires Browser SDK 2.27.0 or higher. Set `config.autocapture.webVitals` to `true` to enable web vitals tracking: ```ts amplitude.init(AMPLITUDE_API_KEY, OPTIONAL_USER_ID, { autocapture: { webVitals: true, }, }); ``` #### Metrics captured The web vitals autocapture feature captures the following Core Web Vitals metrics. - [INP](https://web.dev/articles/inp) - [TTFB](https://web.dev/articles/ttfb) - [LCP](https://web.dev/articles/lcp) - [FCP](https://web.dev/articles/fcp) - [CLS](https://web.dev/articles/cls) #### Event properties The `[Amplitude] Web Vitals` event includes the following properties: | Property | Description | | --- | --- | | `[Amplitude] Page Domain` | The hostname of the current page | | `[Amplitude] Page Location` | The full URL of the current page | | `[Amplitude] Page Path` | The pathname of the current page | | `[Amplitude] Page Title` | The title of the current page | | `[Amplitude] Page URL` | The URL of the current page without query parameters | | `[Amplitude] LCP` | [Largest Contentful Paint](https://github.com/GoogleChrome/web-vitals?tab=readme-ov-file#lcpmetric) (if available) | | `[Amplitude] FCP` | [First Contentful Paint](https://github.com/GoogleChrome/web-vitals?tab=readme-ov-file#fcpmetric) (if available) | | `[Amplitude] INP` | [Interaction to Next Paint](https://github.com/GoogleChrome/web-vitals?tab=readme-ov-file#inpmetric) (if available) | | `[Amplitude] CLS` | [Cumulative Layout Shift](https://github.com/GoogleChrome/web-vitals?tab=readme-ov-file#clsmetric) (if available) | | `[Amplitude] TTFB` | [Time to First Byte](https://github.com/GoogleChrome/web-vitals?tab=readme-ov-file#ttfbmetric) (if available) | ## Track an event Events represent how users interact with your application. For example, the Button Clicked event might be an action you want to track. ```ts // Track a basic event. amplitude.track("Button Clicked"); // Track events with optional properties. const eventProperties = { buttonColor: "primary", }; amplitude.track("Button Clicked", eventProperties); ``` ## Track video playback > **Warning:** Experimental API > > The `trackVideo` API is experimental and may change without notice. Use `trackVideo` to capture `Video Started` and `Video Stopped` events from an HTML video element or supported embedded player. The function returns either a cleanup function or an `Error`. ```ts import * as amplitude from "@amplitude/analytics-browser"; const video = document.querySelector("video"); if (video) { const stopTracking = amplitude.trackVideo(amplitude, video, { extraEventProperties: { placement: "homepage" }, }); if (typeof stopTracking === "function") { // Call stopTracking() when you no longer want to capture video events. } } ``` ## Verify your setup and ingestion > **Tip:** Verify first event ingestion > > By default, Browser SDK 2 queues events and uploads them every 1 second or after 30 events, whichever comes first. To check the event immediately, run `await amplitude.flush()` after `track()`. > > 1. Open your browser's developer tools and select **Network**. > 2. Enter this value in the request filter, then run the tracking code: > > ```text > api2.amplitude.com > ``` > 3. Select the ingestion request and inspect its response and payload. A `200 OK` response confirms that Amplitude accepted the event. A `400 Bad Request` response means that Amplitude rejected the payload; inspect the response body for the validation error and compare it with the request payload. > 4. Open [User Lookup activity](https://amplitude.com/docs/analytics/user-data-lookup#activity), find the event's user or device ID, and enable **Live event updates**. Confirm that the event appears in the activity stream. You can also pass a `BaseEvent` object to `track`. For more information, review the [BaseEvent](https://amplitude.github.io/Amplitude-TypeScript/interfaces/_amplitude_analytics_browser.Types.BaseEvent.html) interface for all available fields. ```ts const event_properties = { buttonColor: "primary", }; const event = { event_type: "Button Clicked", event_properties, groups: { role: "engineering" }, group_properties: { groupPropertyKey: "groupPropertyValue" }, }; amplitude.track(event); ``` ## Track events to multiple projects By default, Amplitude SDKs send data to one Amplitude project. To send data to more than one project, add an instance of the Amplitude SDK for each project you want to receive data. Then, pass instance variables to wherever you want to call Amplitude. Each instance allows for independent `apiKey`, `userId`, `deviceId`, and `settings` values. ```ts const defaultInstance = amplitude.createInstance(); defaultInstance.init(API_KEY_DEFAULT); const envInstance = amplitude.createInstance(); envInstance.init(API_KEY_ENV, { instanceName: "env", }); ``` ## User properties User properties are details like device details, user preferences, or language that help you understand your users at the time they performed an action in your app. Identify sets the user properties of a particular user without sending any event. The SDK supports the operations `set`, `setOnce`, `unset`, `add`, `append`, `prepend`, `preInsert`, `postInsert`, `remove`, and `clearAll` on individual user properties. Declare the operations through a provided Identify interface. You can chain together multiple operations in a single Identify object. Then pass the Identify object to the Amplitude client to send to the server. > **Note:** Identify calls > > If the SDK sends the Identify call after the event, the details of the call appear immediately in the user's profile in Amplitude. Results don't appear in chart results until the SDK sends another event after Identify. Identify calls affect events that happen after it. For more information, refer to [Overview of user properties and event properties](https://amplitude.com/docs/data/user-properties-and-events). ### Set a user property The Identify object provides controls for setting user properties. To set a user property: 1. Instantiate an Identify object. 2. Call methods on that object. 3. Instruct the SDK to make a call with the Identify object. ```ts const identifyEvent = new amplitude.Identify(); // Use methods in the following sections to update the Identify object amplitude.identify(identifyEvent); ``` #### Identify.set This method sets the value of a user property. For example, you can set a role property of a user. ```ts const identifyEvent = new amplitude.Identify(); identifyEvent.set("location", "LA"); amplitude.identify(identifyEvent); ``` #### Identify.setOnce This method sets the value of a user property only one time. Subsequent calls using `setOnce()` are ignored. For example, you can set an initial login method for a user. `setOnce()` ignores later calls. ```ts const identifyEvent = new amplitude.Identify(); identifyEvent.setOnce("initial-location", "SF"); identify(identifyEvent); ``` #### Identify.add This method increments a user property by a numerical value. If the user property doesn't have a value set yet, the SDK initializes it to `0` before incrementing. For example, you can track a user's travel count. ```ts const identifyEvent = new amplitude.Identify(); identifyEvent.add("travel-count", 1); amplitude.identify(identifyEvent); ``` #### Identify.unset This method removes a user property from a user profile. Use `unset` when you no longer need a property or want to remove it completely. ```ts const identifyEvent = new amplitude.Identify(); identifyEvent.unset("location"); amplitude.identify(identifyEvent); ``` ### Arrays in user properties Call the `prepend`, `append`, `preInsert`, or `postInsert` methods to use arrays as user properties. #### Identify.prepend This method prepends a value or values to a user property array. If the user property doesn't have a value set yet, the SDK initializes it to an empty list before prepending the new values. ```ts const identifyEvent = new Identify(); identifyEvent.prepend("visited-locations", "LAX"); identify(identifyEvent); ``` #### Identify.append This method appends a value or values to a user property array. If the user property doesn't have a value set yet, the SDK initializes it to an empty list before appending the new values. ```ts const identifyEvent = new amplitude.Identify(); identifyEvent.append("visited-locations", "SFO"); amplitude.identify(identifyEvent); ``` #### Identify.postInsert This method post-inserts a value or values to a user property if the value doesn't exist in the user property yet. Post-insert means inserting the values at the end of a given list. If the user property doesn't have a value set yet, the SDK initializes it to an empty list before post-inserting the new values. If the user property has an existing value, this method is a no-op. ```ts const identifyEvent = new amplitude.Identify(); identifyEvent.postInsert("unique-locations", "SFO"); amplitude.identify(identifyEvent); ``` #### Identify.remove This method removes a value or values to a user property if it exists in the user property. Remove means remove the existing values from the given list. If the user property has an existing value, this method is a no-op. ```ts const identifyEvent = new amplitude.Identify(); identifyEvent.remove("unique-locations", "JFK"); amplitude.identify(identifyEvent); ``` #### Identify.clearAll This method removes all user properties from the user. Use `clearAll` with care because it's irreversible. ```ts const identifyEvent = new amplitude.Identify(); identifyEvent.clearAll(); amplitude.identify(identifyEvent); ``` ## User groups 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:** > > If Joe is in 'orgId' '15', then the `groupName` is `15`. > > ```ts > // set group with a single group name > amplitude.setGroup("orgId", "15"); > ``` > > If Joe is in 'sport' 'soccer' and 'tennis', then the `groupName` is `["tennis", "soccer"]`. > > ```ts > // set group with multiple group names > amplitude.setGroup("sport", ["soccer", "tennis"]); > ``` Pass an `Event` object with `groups` to a Track call to set an **event-level group**. With event-level groups, the group designation applies only to the specific logged event, and doesn't persist to the user unless you explicitly set it with `setGroup`. ```ts amplitude.track({ event_type: "event type", event_properties: { eventPropertyKey: "event property value" }, groups: { orgId: "15" }, }); ``` ## Group properties Use the Group Identify API to set or update the properties of particular groups. These updates only affect events from this point onward. The `groupIdentify()` method accepts a group type and group name string parameter, as well as an Identify object that the SDK applies to the group. ```ts const groupType = "plan"; const groupName = "enterprise"; const groupIdentifyEvent = new amplitude.Identify(); groupIdentifyEvent.set("key1", "value1"); amplitude.groupIdentify(groupType, groupName, groupIdentifyEvent); ``` ## Track revenue The preferred method of tracking revenue for a user is to use `revenue()` in conjunction with the provided Revenue interface. Revenue instances store each revenue transaction and allow you to define several special revenue properties (like `revenueType` and `productId`) that Amplitude's Event Segmentation and Revenue LTV charts use. Pass these Revenue instance objects into `revenue()` to send as revenue events to Amplitude. This lets Amplitude automatically display data relevant to revenue in the platform. You can use this to track both in-app and non-in-app purchases. > **Tip:** > > Amplitude recommends to also enable [product array](https://amplitude.com/docs/analytics/charts/cart-analysis) tracking method to get the most information possible. To track revenue from a user, call revenue each time a user generates revenue. In this example, the user purchased 3 units of a product at $3.99. ```ts const event = new amplitude.Revenue() .setProductId("com.company.productId") .setPrice(3.99) .setQuantity(3) .setRevenueType("purchase"); amplitude.revenue(event); ``` This example shows tracking revenue with currency type: ```ts const event = new amplitude.Revenue() .setProductId("com.company.productId") .setPrice(3.99) .setQuantity(3) .setRevenueType("purchase") .setCurrency("JPY"); amplitude.revenue(event); ``` This example shows tracking revenue with additional properties: ```ts const event = new amplitude.Revenue() .setProductId("com.company.productId") .setPrice(3.99) .setQuantity(3) .setRevenueType("purchase") .setEventProperties({ category: "electronics", brand: "Acme", }); amplitude.revenue(event); ``` ### Revenue interface Revenue objects support the following properties. Use the corresponding setter methods to assign values. | Name | Setter Method | Description | Default Value | | --- | --- | --- | --- | | `productId` | `setProductId()` | Optional. `string`. An identifier for the product. Amplitude recommends something like the Google Play Store product ID. | Empty string. | | `quantity` | `setQuantity()` | Required. `number`. The quantity of products purchased. `revenue = quantity * price`. | `1` | | `price` | `setPrice()` | Required. `number`. The price of the products purchased, and this can be negative. `revenue = quantity * price`. | `null` | | `revenueType` | `setRevenueType()` | Optional, but required for revenue verification. `string`. The revenue type (for example, tax, refund, income). | `null` | | `currency` | `setCurrency()` | Optional. `string`. The currency type for the revenue (for example, `'USD'`, `'JPY'`, `'EUR'`). | `null` | | `receipt` | `setReceipt()` | Optional. `string`. The receipt identifier of the revenue. | `null` | | `receiptSignature` | `setReceiptSignature()` | Optional, but required for revenue verification. `string`. The receipt signature of the revenue. | `null` | | `eventProperties` | `setEventProperties()` | Optional. `{ [key: string]: any }`. An object of event properties to include in the revenue event. | `null` | ## Flush the event buffer The `flush` method triggers the client to send buffered events immediately. ```ts amplitude.flush(); ``` By default, the Browser SDK calls `flush` automatically at an interval. If you want to flush all events, control the async flow with the optional Promise interface, for example: ```ts amplitude.init(API\_KEY).promise.then(function() { amplitude.track('Button Clicked'); amplitude.flush(); }); ``` ## Custom user identifier If your application has a login system that you want to track users with, call `setUserId` to update the user's identifier. ```ts amplitude.setUserId("user@amplitude.com"); ``` ## Custom session identifier Assign a new session ID with `setSessionId`. When you set a custom session ID, make sure the value is in milliseconds since epoch (Unix Timestamp). ```ts amplitude.setSessionId(Date.now()); ``` ## Custom device identifier Assign a new device ID with `deviceId`. When you set a custom device ID, make sure the value is sufficiently unique. Amplitude recommends using a UUID. ```ts amplitude.setDeviceId(uuid()); ``` ## Reset when the user logs out Use `reset` as a shortcut to anonymize users after they log out. `reset` does the following: 1. Sets `userId` to `undefined`. 2. Sets `deviceId` to a new UUID value. With an undefined `userId` and a new `deviceId`, the user appears to Amplitude as a new user. ```ts amplitude.reset(); ``` ## Read and update identity state Use the identity accessors to read the current SDK state: ```ts const userId = amplitude.getUserId(); const deviceId = amplitude.getDeviceId(); const sessionId = amplitude.getSessionId(); const optOut = amplitude.getOptOut(); const identity = amplitude.getIdentity(); ``` Use `setIdentity` to update the user ID, device ID, and user properties together. When `userProperties` changes, the SDK sends an Identify event with `$set` operations for the new properties. Replacing local user properties doesn't unset removed properties on Amplitude's servers. Use `Identify.unset()` to remove a server-side user property. ```ts amplitude.setIdentity({ userId: "user-123", deviceId: "device-456", userProperties: { plan: "premium" }, }); ``` Call `extendSession()` to update the last user interaction time without tracking an event: ```ts amplitude.extendSession(); ``` ## Opt users out of tracking Set `setOptOut` to `true` to disable logging for a specific user. ```ts amplitude.setOptOut(true); ``` Amplitude doesn't save or send events to the server while `setOptOut` is enabled. The setting persists across page loads. Set `setOptOut` to `false` to re-enable logging. ```ts amplitude.setOptOut(false); ``` ## Optional tracking By default, the SDK tracks these properties automatically. You can override this behavior by passing a configuration called `trackingOptions` when initializing the SDK, setting the appropriate options to false. | Tracking Options | Default | | --- | --- | | `ipAddress` | `true` | | `language` | `true` | | `platform` | `true` | ```ts amplitude.init(AMPLITUDE_API_KEY, { trackingOptions: { ipAddress: false, language: false, platform: false, }, }); ``` ## Callback All asynchronous APIs are optionally awaitable through a Promise interface. This also serves as a callback interface. #### Promise ```ts amplitude.init("apikey", "12321.com").promise.then(function () { // init callback }); amplitude.track("Button Clicked").promise.then(function (result) { result.event; // {...} (The final event object sent to Amplitude) result.code; // 200 (The HTTP response status code of the request. result.message; // "Event tracked successfully" (The response message) }); ``` #### async/await ```ts // Using async/await const initResult = await amplitude.init("apikey", "12321.com").promise; const results = await amplitude.track("Button Clicked").promise; result.event; // {...} (The final event object sent to Amplitude) result.code; // 200 (The HTTP response status code of the request. result.message; // "Event tracked successfully" (The response message) ``` ## Plugins Plugins allow you to extend Amplitude SDK's behavior by, for example, modifying event properties (enrichment plugin) or sending to third-party endpoints (destination plugin). A plugin is an `Object` with optional fields `name` and `type` and methods `setup()`, `execute()`, and `teardown()`. ### add The `add` method adds a plugin to Amplitude. ```ts amplitude.add(new Plugin()); ``` ### remove The `remove` method removes the given plugin name from the client instance if it exists. ```ts amplitude.remove(plugin.name); ``` ### Create a custom plugin | Field / Function | Description | | --- | --- | | `plugin.name` | Optional. The name field is an optional property that allows you to reference the plugin for deletion purposes. If you don't provide one, Amplitude assigns a random name when you add the plugin. If you don't plan to delete your plugin, you can skip assigning a name. | | `plugin.type` | Optional. The type field is an optional property that defines the type of plugin you are creating. Refer to the `plugin.execute()` function below to distinguish the two types. If not defined, the plugin defaults to an enrichment type. | | `plugin.setup()` | Optional. The setup function is an optional method that the SDK calls when you add the plugin or on first init, whichever happens later. This function accepts two parameters: 1) Amplitude configuration; and 2) Amplitude instance. This is useful for setup operations and tasks that depend on either the Amplitude configuration or instance. Examples include assigning baseline values to variables, setting up event listeners, and many more. | | `plugin.execute()` | Optional for type:enrichment. For enrichment plugins, execute function is an optional method that the SDK calls on each event. This function must return a new event, otherwise, the SDK drops the passed event from the queue. This is useful for cases where you need to add or remove properties from events, filter events, or perform any operation for each event tracked. **For destination plugins**, execute function is a required method that the SDK calls on each event. This function must return a response object with keys: `event` (BaseEvent), `code` (number), and `message` (string). This is useful for sending events for third-party endpoints. | | `plugin.teardown()` | Optional. The teardown function is an optional method that the SDK calls when Amplitude re-initializes. This is useful for resetting unneeded persistent state that setup or execute methods create or set. Examples include removing event listeners or mutation observers. | ### Plugin examples #### Enrichment Here's an example of an enrichment plugin that includes an extra event property `page_url` to all events. ```ts const enrichPageUrlPlugin = (): EnrichmentPlugin => { return { execute: async (event: Event) => { event.event_properties = { ...event.event_properties, page_url: location.href, }; return event; }, }; }; amplitude.add(enrichPageUrlPlugin()); amplitude.init(API_KEY); ``` #### Destination Here's an example of a destination plugin that sends each tracked event to a custom server URL using Fetch API. ```ts const customDestination = (customUrl: string): DestinationPlugin => { return { type: "destination", execute: async (event: Event) => { const payload = { k: "apikey", d: event, }; const response = await fetch(customUrl, { method: "POST", headers: { "Content-Type": "application/json", Accept: "\*/\*", }, body: JSON.stringify(payload), }); return { code: response.status, event: event, message: response.statusText, }; }, }; }; amplitude.init(API_KEY); amplitude.add(myDestinationPlugin("https://custom.url.com")); ``` ### Available plugins Amplitude provides several official plugins to extend the Browser SDK functionality: #### Page URL enrichment plugin Autocapture enables the [page URL enrichment plugin](https://amplitude.com/docs/sdks/analytics/browser/page-url-enrichment-plugin) by default. The plugin automatically adds page URL-related properties to all events, including current page information, previous page location, and page type classification. To disable page URL enrichment, set `autocapture.pageUrlEnrichment` to `false`: ```ts amplitude.init(API_KEY, { autocapture: { pageUrlEnrichment: false, }, }); ``` For custom configuration or if you disabled autocapture entirely, you can still add the plugin manually: ```ts import { pageUrlEnrichmentPlugin } from "@amplitude/plugin-page-url-enrichment-browser"; const pageUrlEnrichment = pageUrlEnrichmentPlugin(); amplitude.add(pageUrlEnrichment); amplitude.init(API_KEY); ``` #### Custom enrichment plugin The [Custom Enrichment plugin](https://amplitude.com/docs/sdks/analytics/browser/custom-enrichment-plugin) runs an enrichment function against every event the SDK tracks. Amplitude stores that function in your project's remote configuration. The plugin is off by default, and requires version 2.37.0 or later. This plugin is separate from the custom plugins you add with `amplitude.add()`. Enabling it doesn't change how your own plugins behave. To enable it, set `customEnrichment` to `true`: ```ts amplitude.init(API_KEY, { customEnrichment: true, }); ``` ## Troubleshooting and debugging Debugging in a browser can help you identify problems related to your code's implementation, as well as potential issues within the SDKs you're using. Here's a basic guide on how to use the browser's built-in Developer Tools (DevTools) for debugging. ### Console You can find JavaScript errors in _Inspect > Console_, which might have the details about the line of code and file that caused the problem. The console also allows you to execute JavaScript code in real time. - Enable debug mode by following these [instructions](#debugging). Then, with the default logger, the SDK outputs extra function context information to the developer console when you invoke any SDK public method, which can help with debugging. - Amplitude supports SDK deferred initialization. The SDK dispatches events tracked before initialization after the initialization call. If you can't send events but can send the event successfully after entering `amplitude.init(API_KEY, 'USER_ID')` in the browser console, your `amplitude.init` call might not have triggered in your codebase or you aren't using the correct Amplitude instance during initialization. Therefore, check your implementation. ### Network request Use the _Inspect > Network_ tab to view all network requests your page made. Search for the Amplitude request. Check the response code and ensure that the response payload is as expected. ### Instrumentation Explorer Chrome extension The Amplitude Instrumentation Explorer is an extension available in the Google Chrome Web Store. The extension captures each Amplitude event you trigger and displays it in the extension popup. Ensure that the SDK sent the event successfully and check the context in the event payload. ### Common issues The following are common issues specific to Browser SDK. For more general common issues, refer to [SDK Troubleshooting and Debugging](https://amplitude.com/docs/sdks/sdk-debugging). #### Ad blocker `Ad Blocker` might lead to event dropping. The following errors indicate that an `Ad Blocker` affected tracking. When loading through a script tag, an error may appear in the console or network tab while loading the SDK script. When loaded with npm package, there could be errors in the network tab when trying to send events to the server. The errors might vary depending on the browser. - Chrome (Ubuntu, MacOS) Console: error net::ERR\_BLOCKED\_BY\_CLIENT Network: status (blocked:other) - Firefox (Ubuntu) Console: error text doesn’t contain any blocking-specific info Network: Transferred column contains the name of plugin Blocked by uBlock Origin - Safari (MacOS) Console: error contains text Content Blocker prevented frame ... from loading a resource from ... Network: it looks like blocked requests aren't listed. Not sure if it’s possible to show them. Amplitude recommends using a proxy server to avoid this situation. #### Cookies related Here is the [information](#cookie-management) the SDK stores in the cookies. This means that client behavior, like disabling cookies or using a private browser, window, or tab, affects the persistence of these saved values in the cookies. If these values aren't persistent or aren't increasing by one, that could be the reason. #### CORS Cross-Origin Resource Sharing (CORS) is a security measure browsers implement to restrict how a web page can request resources from a different domain. It might cause this issue if you used `setServerURL`. `Access to fetch at 'xxx' from origin 'xxx' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.` Cross-origin resource sharing (CORS) prevents a malicious site from reading another site's data without permission. The error message suggests that the server you're trying to access isn't allowing your origin to access the requested resource. This is due to the lack of the `Access-Control-Allow-Origin` header in the server's response. - If you have control over the server, you can update the server's CORS policy. Add the `Access-Control-Allow-Origin` header to the server's responses. This allows your origin to make requests. The value of `Access-Control-Allow-Origin` can be `*` to allow all origins, or it can be the specific URL of your web page. - If you don't have control over the server, you can set up a proxy server that adds the necessary CORS headers. The web page makes requests to the proxy, which then makes requests to the actual server. The proxy adds the `Access-Control-Allow-Origin` header to the response before sending it back to the web page. If you have set up an API proxy and run into configuration issues related to that on a platform you've selected, that's no longer an SDK issue but an integration issue between your application and the service provider. #### Events fired but no network requests If you [set the logger to "Debug" level](#debugging) and see track calls in the developer console, your code has called the `track()` method. If you don't see the corresponding event in Amplitude, the Amplitude Instrumentation Explorer Chrome extension, or the network request tab of the browser, the SDK didn't send the event to Amplitude. The SDK fires events and places them in its internal queue upon a successful `track()` call, but sometimes these queued events may not send successfully. This can happen when the browser cancels an in-progress HTTP request. For example, if you close the browser or leave the page. This most often happens when an event fires just before a redirect or navigation, such as a login event that immediately loads a new page. There are a few ways to address this issue: 1. By default, the `fetch` transport sends events with `keepalive`, which lets requests finish even after the page unloads. This handles most navigation cases automatically for request bodies up to 16 KB. Confirm that keepalive isn't disabled and that the event batch is within the size limit. For more information, refer to the [Survive page navigation with keepalive](#survive-page-navigation-with-keepalive) section. 2. For payloads larger than the keepalive limit, set the transport to `beacon` during initialization or upon page exit. `sendBeacon` sends events in the background but doesn't return server responses like `4xx` or `5xx`, so it doesn't retry on failure. For more information, refer to the [sendBeacon](#use-sendbeacon) section. 3. To make `track()` synchronous, [add the `await` keyword](#callback) before the call. ## Advanced topics ### Cross-domain tracking You can track anonymous behavior across two different domains. Amplitude identifies anonymous users by their device IDs which must be passed between the domains. To maintain the same session and ensure a continuous user journey, also pass session IDs to the other domain. > **Note:** > > Starting from `v2.8.0`, the SDK supports getting the device ID from the URL parameter `ampDeviceId`. The SDK configuration, for example, `init('API_KEY', { deviceId: 'custom-device-id' })`, still takes precedence over the URL parameter. Previous versions of the SDK supported the `deviceId` URL parameter. The SDK still supports this option for backward compatibility, but `ampDeviceId` takes precedence if you set both. You don't need to change your code if you upgrade to versions higher than `v2.8.0`, but Amplitude recommends it. For example: - Site 1: `www.example.com` - Site 2: `www.example.org` Users who start on Site 1 and then navigate to Site 2 must have the device ID generated from Site 1 passed as a parameter to Site 2. Site 2 then needs to initialize the SDK with the device ID. The SDK can parse the URL parameter automatically if `deviceId` is in the URL query parameters. Starting from `v2.8.0`, the SDK can automatically get session ID from the URL to keep the same session and ensure a continuous user journey. 1. From Site 1, grab the device ID from `getDeviceId()` and the session ID from `getSessionId()`. 2. Pass the device ID and session ID to Site 2 through a URL parameter when the user navigates. (for example: `www.example.com?ampDeviceId=device_id_from_site_1&SessionId=1716245958483`) 3. Initialize the Amplitude SDK on Site 2 with `init('API_KEY', null)`. If you don't set the `deviceId` and `sessionId` in `init('API_KEY', null, { deviceId: 'custom-device-id', sessionId: 1716245958483 })`, the SDK automatically falls back to using the URL parameters respectively. #### Evaluation window with ampTimestamp > **Note:** > > This feature requires @amplitude/analytics-browser@2.21.1 and above. To improve security and prevent the use of stale session or device IDs, you can include an `ampTimestamp` parameter that acts as an evaluation window. The SDK only uses `ampSessionId` and `ampDeviceId` URL parameters if the `ampTimestamp` value is in the future (greater than the current time). For example: ```plaintext www.example.com?ampDeviceId=device_id&SessionId=session_id&Timestamp=1640995500000 ``` When `ampTimestamp` expires (is less than the current time), the SDK ignores the `ampSessionId` and `ampDeviceId` parameters. The SDK falls back to generating new values or using stored values from cookies. If you don't provide `ampTimestamp`, the SDK behaves as before for backward compatibility. This feature ensures that cross-domain tracking parameters remain valid only for a limited time window. This prevents potential security issues from long-lived URLs with embedded tracking parameters. Amplitude recommends that you follow the same session ID format as the Browser SDK using `Date.now()` because the SDK checks if an event is in session every time it tracks an event. For example: ```typescript // if session ID is set to 12345 // https://www.example.com?ampDeviceId=my-device-id&SessionId=12345 amplitude.init(API_KEY); // session ID is set to 12345 after init() amplitude.track("event"); // session ID is set back to Date.now() // because the tracked "event" is not in the previous session 12345 ``` ### Custom HTTP request headers Use the `transport` configuration option to attach custom HTTP headers to event upload requests. Instead of passing a transport name string, pass an object with `transport` and `headers` properties. This is useful for scenarios like routing requests through a proxy server that requires specific headers. > **Note:** > > Custom headers only work with `fetch` and `xhr` transports. When using the `beacon` transport, the browser doesn't support custom headers due to limitations of the [sendBeacon API](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon). ```ts amplitude.init(API_KEY, { transport: { type: "fetch", headers: { "X-Custom-Header": "custom-value", Authorization: "Bearer your-token", }, }, }); ``` You can also use the `xhr` transport with custom headers: ```ts amplitude.init(API_KEY, { transport: { type: "xhr", headers: { "X-Custom-Header": "custom-value", }, }, }); ``` ### Request body compression The Browser SDK supports gzip compression for event upload request bodies to reduce bandwidth usage and improve upload performance. Compression is especially beneficial when sending large batches of events. #### How compression works The SDK automatically compresses request bodies when: - The payload size is 2KB or larger. - The browser supports the `CompressionStream` API (available in modern browsers). - The transport type is `fetch` or `xhr` (the SDK doesn't support compression with the `beacon` transport). When using Amplitude's default ingestion endpoints (`https://api2.amplitude.com`), the SDK automatically enables compression. When using a custom `serverUrl` (for example, a proxy server), you must explicitly enable compression by setting `enableRequestBodyCompression` to `true`. > **Note:** > > The `beacon` transport doesn't support compression because the [sendBeacon API](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon) doesn't allow setting custom headers, which are required for gzip compression. #### Enable compression for custom servers If you route events through a custom proxy server, enable compression by setting `enableRequestBodyCompression` to `true`: ```ts amplitude.init(API_KEY, { serverUrl: "https://your-proxy.example.com/events", enableRequestBodyCompression: true, }); ``` Your proxy server must support gzip-compressed request bodies and handle the `Content-Encoding: gzip` header. #### Browser compatibility Request body compression requires the `CompressionStream` API, which is available in: - Chrome 80+ - Edge 80+ - Safari 16.4+ - Firefox 113+ For browsers that don't support `CompressionStream`, the SDK automatically sends uncompressed payloads. ### Survive page navigation with keepalive By default, the Browser SDK sends events on the `fetch` transport with the [`keepalive`](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit#keepalive) flag enabled. Browsers allow keepalive requests to finish even after the page that started them unloads. As a result, events that fire just before a redirect or navigation reach Amplitude instead of being canceled. A common example is a login event that immediately sends the user to another page. Keepalive applies only to the `fetch` transport. Unlike the `beacon` transport, it preserves gzip compression, custom headers, server responses, and retries. #### Keepalive size limit The [Fetch specification](https://fetch.spec.whatwg.org/#http-network-or-cache-fetch) enforces a shared 64 KiB budget across all in-flight keepalive requests in a document. This budget includes Amplitude analytics, Session Replay, and any keepalive requests your own code makes. To stay within the budget, the SDK applies keepalive only when the request body is 16 KB or smaller. Larger payloads send as a standard `fetch` request with no size limit, but those requests don't survive navigation, which matches the behavior in earlier versions. Typical event batches are well under the limit, so nearly all traffic benefits. If the browser rejects a keepalive request because the shared budget is exhausted mid-session, the SDK retries it on the next flush. The result is a delay, not data loss. #### Disable keepalive Keepalive is on by default. To turn it off, set `enableKeepalive` to `false` in the transport configuration. This option applies only to the `fetch` transport. ```ts amplitude.init(API_KEY, { transport: { type: "fetch", enableKeepalive: false, }, }); ``` On browsers that don't support keepalive, the SDK ignores the option and sends requests normally. ### Use sendBeacon > **Note:** > > The default `fetch` transport already sends events with [`keepalive`](#survive-page-navigation-with-keepalive), which survives page navigation while keeping gzip compression, custom headers, server responses, and retries. The `beacon` transport doesn't support those features, so reach for it only when keepalive doesn't fit your case, such as payloads larger than the keepalive limit. Unlike standard network requests, `sendBeacon` sends events in the background, even if the user closes the browser or leaves the page. > **Warning:** > > `sendBeacon` sends events in the background. As a result, events that `sendBeacon` dispatches don't return server responses. Note the following if you use `sendBeacon`: > > 1. The SDK doesn't retry requests, including failed requests with 4xx or 5xx responses, so events may be lost. > 2. The SDK can't guarantee event order, because `sendBeacon` may send events in parallel. This can leave some UTM properties unset, for example for session start events. In contrast, while using `fetch`, the SDK waits for responses before proceeding, guaranteeing event order. #### Set the transport to use sendBeacon for all events To send an event using `sendBeacon`, set the transport SDK option to `beacon` in one of two ways: ```ts amplitude.init(API_KEY, "user@amplitude.com", { transport: TransportType.SendBeacon, // To make sure the SDK schedules the event right away. flushIntervalMillis: 0, flushQueueSize: 1, }); ``` #### Set the transport to use beacon only when exiting page Amplitude recommends adding your own event listener for pagehide event. ```ts window.addEventListener("pagehide", () => { amplitude.setTransport("beacon"); // Sets https transport to use `sendBeacon` API amplitude.flush(); }); ``` ### Content Security Policy (CSP) If your web app configures the strict Content Security Policy (CSP) for security concerns, adjust the policy to allow the Amplitude domains: - When using ["Script Loader"](https://github.com/amplitude/Amplitude-TypeScript/tree/main/packages/analytics-browser#installing-via-script-loader), add `https://*.amplitude.com` to `script-src`. - Add `https://*.amplitude.com` to `connect-src`. ### Cookie management The Browser SDK uses cookie storage to persist information that multiple subdomains of the same domain may likely want to share. This includes information like user sessions and marketing campaigns, which the SDK stores in separate cookie entries. #### Cookie prefix - **AMP**: The SDK creates user session cookies with `AMP` prefix and the first ten digits of the API key: `AMP_{first_ten_digits_API_KEY}`. - **AMP\_MKTG**: The SDK creates marketing campaign cookies with `AMP_MKTG` and the first ten digits of the API key: `AMP_MKTG_{first_ten_digits_API_KEY}`. - **AMP\_TEST**: On initialization, the SDK creates a cookie with `AMP_TEST` prefix to check whether cookie storage is working properly. Then the SDK sets the value as the current time, retrieves the cookie by a key, and checks if the retrieved value matches the original set time. You **can safely delete** the `AMP_TEST` prefix cookies if, for some reason, the SDK didn't successfully delete them. - **AMP\_TLDTEST**: On initialization, the SDK creates a cookie with `AMP_TLDTEST` prefix to find a subdomain that supports cookie storage. For example, when checking for cookie support on `https://analytics.amplitude.com/amplitude/home`, the SDK first tries to find a subdomain that matches the root domain (`amplitude.com`) and then falls back to the full domain (`analytics.amplitude.com`). You **can safely delete** the `AMP_TLDTEST` prefix cookies if, for some reason, the SDK didn't successfully delete them. #### Cookie domain By default, the SDK assigns these cookies to the top-level domain that supports cookie storage. The SDK can share cookies on multiple subdomains, which allows for a consistent user experience across all subdomains. For example, if a user logs into the website on one subdomain (`data.amplitude.com`) where you initialize the SDK. On initialization, the SDK assigns cookies to `.amplitude.com`. If the user then navigates to another subdomain (`analytics.amplitude.com`), shared cookies share the login information across subdomains. #### Cookie data The SDK creates two types of cookies: user session cookies and marketing campaign cookies. #### User session cookies | Name | Description | | --- | --- | | `optOut` | Required. A flag to opt this device out of Amplitude tracking. If you set this flag, the SDK doesn't store additional information for the user. | | `userId` | Upon user log-in, if you send this value, the SDK stores it in the cookie. Set this to uniquely identify their users (non-anonymous navigation). The SDK stores it encoded using Base64. | | `deviceId` | A randomly generated string. It persists unless a user clears their browser cookies or browses in private mode. Even if a user consistently uses the same device and browser, the device ID can still vary. | | `sessionId` | A Unix timestamp in milliseconds that identifies the session. | | `lastEventTime` | Time of the last event, used to determine when to expire and create a new session ID. | | `lastEventId` | ID of the last event. | #### Marketing campaign cookies | Name | Description | | --- | --- | | `utm_campaign` | This identifies a specific campaign used (for example, "summer\_sale") | | `utm_content` | This identifies what brought the user to the site. Commonly used for A/B testing (for example, "banner-link", "text-link") | | `utm_id` | An optional parameter for tracking unique IDs or transaction IDs associated with the link. | | `utm_medium` | This identifies a specific campaign used (for example, "summer\_sale") | | `utm_source` | This identifies which website sent the traffic (for example, Google, Facebook) | | `utm_term` | This identifies paid search terms used (for example, product+analytics) | | `referrer` | The last page the user was on (for example, `https://amplitude.com/behavioral-analytics-platform?ref=nav`) | | `referring_domain` | The domain that the user was last on (for example, `https://amplitude.com`) | | `dclid` | Google campaign manager Click Identifier | | `gbraid` | Google Click Identifier for iOS device from Web to App | | `gclid` | Google Click Identifier from URL parameters | | `fbclid` | Facebook Click Identifier from URL parameters | | `ko_click_id` | Kochava Click Identifier from URL parameters | | `msclkid` | Microsoft Click Identifier | | `ttclid` | TikTok Click Identifier | | `twclid` | Twitter Click Identifier from URL parameter | | `wbraid` | Google Click Identifier for iOS device from App to Web | | `li_fat_id` | LinkedIn member indirect identifier for Members for conversion tracking, retargeting, analytics | | `rdt_cid` | Reddit Click Identifier | #### Disable cookies Opt-out of using cookies by setting `identityStorage` to `localStorage` so that the SDK uses `LocalStorage` instead. `LocalStorage` is a useful alternative, but because access to `LocalStorage` is restricted by subdomain, you can't track anonymous users across subdomains of your product (for example: `www.amplitude.com` versus `analytics.amplitude.com`). ```ts amplitude.init("api-key", null, { identityStorage: "localStorage", }); ``` ### Offline mode > **Note:** Autoflush when reconnecting > > Setting `config.flushIntervalMillis` to a small value like `1` may cause an `ERR_NETWORK_CHANGED` error. Beginning with version 2.4.0, the Amplitude Browser SDK supports offline mode. The SDK checks network connectivity every time it tracks an event. If the device is connected to network, the SDK schedules a flush. If not, it saves the event to storage. The SDK also listens for changes in network connectivity and schedules a flush of all stored events when the device reconnects, based on the `config.flushIntervalMillis` setting. To disable offline mode, add `offline: amplitude.Types.OfflineDisabled` to the `amplitude.init()` call, as in the following example. ```ts amplitude.init(AMPLITUDE_API_KEY, { offline: amplitude.Types.OfflineDisabled, }); ``` ### Marketing attribution tracking Amplitude tracks marketing attribution and excludes all referrers from subdomains by default. Learn more about [exclude referrers](#exclude-referrers) and [exclude internal referrers](#exclude-internal-referrers). After you enable marketing attribution tracking, Amplitude generates `identify` events to assign the campaign values as user properties in specific scenarios. Refer to the following section to learn when Amplitude tracks marketing attribution and updates user properties. #### Tracking scenarios Amplitude tracks changes in marketing attribution in two scenarios: during SDK initialization and event processing. ##### Amplitude SDK initialization (Hard page refresh) - At the start of a session, the referrer isn't excluded and campaign has any change or customer first visit. - In the middle of the session, the referrer isn't excluded, not direct traffic, and campaign has any change. ![Diagram of whether tracking a campaign on SDK initialization](https://amplitude.com/docs/images/sdk/isNewCampaign.drawio.svg) To debug, you can get the referrer by typing `document.referrer` in your Browser console and compare it with your `config.autocapture.attribution.excludeReferrers`. If `document.referrer` is empty, Amplitude considers it direct traffic. You can get the session ID under `AMP_{last 10 digits of your API key}` on the _Cookies_ tab of the [Amplitude Chrome extension](https://amplitude.com/docs/data/chrome-extension-debug) and get the previous campaign stored under `AMP_MKTG_{last 10 digits of your API key}`. ##### Processing the event - At the start of a session, the referrer isn't excluded, and campaign has any change. For more information, refer to the scenarios outlined below that demonstrate when Amplitude does or doesn't track marketing attribution. These examples are illustrative, not exhaustive. Tracking occurs when either of the following applies: | Rule | Example | | --- | --- | | The current subdomain isn't an excluded referrer. | The referrer doesn't originate from the same domain, or the current subdomain doesn't match any referrer in `config.autocapture.attribution.excludeReferrers`. | | No previous campaign. | A user's initial visit. | | The current campaign differs from the previous campaign stored by the SDK. | Amplitude sends an Identify event that sets the new campaign values and unsets previous campaign fields that are absent from the new campaign, including UTM parameters, click IDs, and referrer fields. | | The referrer domain changes to a new one. | Referrer domain changed from `a.test.com` to `b.test-new.com`. | Amplitude doesn't track marketing attribution under any of the following conditions: | Rule | Example | | --- | --- | | The referrer originates from the same domain with default configuration. | The landing page is `a.test.com`, with the referrer set to `b.test.com`. | | You explicitly exclude a specific referrer domain. | When setting `config.autocapture.attribution.excludeReferrers` = `[a.test.com]`, and the referrer domain is `a.test.com` for the current page. | | The subdomain is specified or matches the regular expression in `config.autocapture.attribution.excludeReferrers`. | Configuration of excludeReferrers involves specific string arrays or a regular expression. | | The user engages in direct traffic within the same session. | During a session, a user clicks on a link without any campaign attribution parameters, including the absence of UTM and click id parameters from an email. | | SPA redirect without page reloading. | During a session, a user clicks on a link without any campaign attribution parameters, including the absence of UTM and click id parameters from an email. | #### Rogue referral problem for SPAs SPAs typically don't experience a true page load after a visitor enters the site, which means the referrer information doesn't update when clicking internal links. UTM parameters may drop during SPA redirects, while the referrer remains unchanged. This is a known issue in the industry. To address this problem, you can either: - Control the page and location parameters, or - Unset the referrer after the first hit. ### Remote configuration Beginning with version 2.10.0, the Amplitude Browser SDK supports remote configuration. > **Note:** Default behavior changed in version 2.16.1 > > Starting in SDK version 2.16.1, `fetchRemoteConfig` **defaults to `true`**. For versions 2.10.0 to 2.16.0, remote configuration defaults to disabled and requires explicit enablement. Autocapture supports remote configuration options for tracking default events. When you enable remote configuration, settings from Amplitude's servers merge with your local SDK configuration, with remote settings taking precedence. Find the remote configuration options in _Data > Settings > Autocapture_. #### Enable or disable remote configuration **For SDK versions 2.16.1 and later:** Remote configuration defaults to enabled. To disable it, explicitly set `fetchRemoteConfig: false`: ```ts amplitude.init(AMPLITUDE_API_KEY, { fetchRemoteConfig: false, // Disable remote config }); ``` **For SDK versions 2.10.0 to 2.16.0:** Remote configuration defaults to disabled. To enable it, set `fetchRemoteConfig: true`: ```ts amplitude.init(AMPLITUDE_API_KEY, { fetchRemoteConfig: true, // Enable remote config (only needed for versions < 2.16.1) }); ``` > **Note:** Configuration merging behavior > > When you enable `fetchRemoteConfig`, the SDK merges remote configuration with local configuration at the feature level. Remote configuration can override specific autocapture features even when you set `autocapture: false` locally. > > How the merging works: > > - If remote configuration specifies a value for an autocapture feature, that value takes precedence. > - If remote configuration doesn't specify a value for a feature, the SDK uses the local configuration value. > - Each autocapture feature such as `sessions`, `pageViews`, and `elementInteractions` merges independently. > > #### Remote config enables specific features when local config disables all > > ```ts > // Local configuration disables all autocapture > amplitude.init(AMPLITUDE_API_KEY, { > autocapture: false, > }); > > // Remote config (set in Data > Settings > Autocapture) enables only: > // - Page Views: enabled > // - Element Interactions: enabled > > // Result: Only Page Views and Element Interactions are tracked > // All other features (sessions, formInteractions, fileDownloads, etc.) remain disabled > ``` > > #### Remote config overrides specific local settings > > ```ts > // Local configuration enables most features > amplitude.init(AMPLITUDE_API_KEY, { > autocapture: { > pageViews: true, > sessions: true, > elementInteractions: true, > formInteractions: true, > }, > }); > > // Remote config (set in Data > Settings > Autocapture): > // - Element Interactions: disabled > // - Frustration Interactions: enabled > > // Result: > // - pageViews: true (from local config) > // - sessions: true (from local config) > // - elementInteractions: false (overridden by remote config) > // - formInteractions: true (from local config) > // - frustrationInteractions: true (set by remote config) > ``` > > #### Remote config when you don't specify local config > > ```ts > // Local configuration doesn't specify autocapture settings > amplitude.init(AMPLITUDE_API_KEY); > > // Remote config (set in Data > Settings > Autocapture): > // - Page Views: enabled > // - Sessions: enabled > > // Result: Only Page Views and Sessions are tracked > // All other features use their default values > ``` > > Set baseline settings locally and adjust specific features remotely through the Amplitude UI without code changes. In Amplitude, navigate to _Data > Settings > Autocapture_ to add or update a remote configuration. #### Proxy remote config requests To proxy remote configuration requests through your own server (for example, to bypass ad blockers), configure the `remoteConfig` option: ```ts amplitude.init(AMPLITUDE_API_KEY, { remoteConfig: { serverUrl: "https://your-proxy.example.com/config", }, }); ``` When you set `remoteConfig.serverUrl`, the SDK sends remote configuration requests to your custom URL instead of Amplitude's endpoints. Analytics events still use `serverUrl` or the default Amplitude endpoints. > **Note:** > > The top-level `fetchRemoteConfig` option is deprecated. Use `remoteConfig.fetchRemoteConfig` instead for new implementations. ================================================================================ # Python SDK URL: https://amplitude.com/docs/sdks/analytics/python/python-sdk ================================================================================ # Python SDK - **Package:** `amplitude-analytics` ([pypi](https://pypi.org/project/amplitude-analytics)) - **Latest version:** 1.2.3 The Python SDK lets you send events to Amplitude. ## Install the SDK Install `amplitude-analytics` with pip: ```bash pip install amplitude-analytics ``` ## Initialize the SDK Initialize the SDK before you instrument any events. The Amplitude project API key is required. You can also pass a config object in this call. Reuse the SDK client instance across requests after initialization. ```python from amplitude import Amplitude client = Amplitude(AMPLITUDE_API_KEY) ``` ## Configure the SDK | Option | Type | Description | Default | | --- | --- | --- | --- | | `api_key` | String (required) | The API key of the Amplitude project. The client instance sends events to this project. Set this when you initialize the client. | `None` | | `flush_queue_size` | Integer | Events wait in the buffer and send in a batch. The SDK flushes the buffer when the number of events reaches `flush_queue_size`. | `200` | | `flush_interval_millis` | Integer | The SDK flushes the buffer every `flush_interval_millis` milliseconds. | `10000` (10 seconds) | | `flush_max_retries` | Integer | The number of times the client retries an event when the request returns an error. | `12` | | `logger` | Logger | The logger instance that the Amplitude client uses. | [python built-in logging](https://docs.python.org/3/library/logging.html#logger-objects): `logging.getLogger(name)` | | `min_id_length` | Integer | The minimum length of `user_id` and `device_id`. | `5` | | `callback` | Function | Client-level callback function. Takes three parameters: `event` (an Event instance), `code` (an integer HTTP response code), and `message` (a string message). | `None` | | `server_zone` | String | The server zone of the project. Supports `EU` and `US`. For EU data residency, set to `EU`. | `US` | | `server_url` | String | The API endpoint URL that the SDK sends events to. The SDK selects this automatically based on `server_zone` and `use_batch`. If you set this field with a string value instead of `None`, the SDK ignores `server_zone` and `use_batch` and uses the string value. | `https://api2.amplitude.com/2/httpapi` | | `use_batch` | Boolean | Whether to use the [batch API](https://amplitude.com/docs/apis/analytics/batch-event-upload). By default, the SDK uses the default `serverUrl`. | `False` | | `storage_provider` | StorageProvider | Creates a storage instance to hold events in the storage buffer. The storage buffer holds events until the SDK sends them. | `InMemoryStorageProvider` | | `opt_out` | Boolean | If `True`, the client doesn't process or send events. | `False` | ```Python def callback_func(event, code, message=None): # callback function that takes three input parameters # event: the event that triggered this callback # code: status code of request response # message: a optional string message for more detailed information client.configuration.api_key = "new api key" client.configuration.flush_max_retries = 5 client.configuration.logger = logging.getLogger(__name__) client.configuration.min_id_length = 7 client.configuration.callback = callback_func client.configuration.server_zone = "EU" client.configuration.use_batch = True client.configuration.server_url = "proxy url that forwarding the requests" client.configuration.opt_out = False ``` ### Configure batching behavior The SDK queues events from the `track` method in memory and flushes them in batches in the background. Customize batch behavior with `flush_queue_size` and `flush_interval_millis`. By default, the SDK runs in regular mode with `serverUrl` set to `https://api2.amplitude.com/2/httpapi`. To send large batches of data at a time, set `use_batch` to `true`. The SDK then sets `serverUrl` to the batch event upload API at `https://api2.amplitude.com/batch`. Regular mode and batch mode use the same flush queue size and flush intervals. ```Python from amplitude import Amplitude client = Amplitude(AMPLITUDE_API_KEY) # Events queued in memory flush when the number of events exceeds the upload threshold # Default value is 200 client.configuration.flush_queue_size = 100 # Events queue flushes every set number of milliseconds # Default value is 10 milliseconds client.configuration.flush_interval_millis = 20000 # 20 seconds ``` ## Track an event Events represent how users interact with your application. For example, "Button Clicked" is a common event. ```python from amplitude import Amplitude, BaseEvent client = Amplitude(AMPLITUDE_API_KEY) # Track a basic event # One of user_id and device_id is required event = BaseEvent(event_type="Button Clicked", user_id="User Id") client.track(event) # Track events with optional properties client.track( BaseEvent( event_type="type of event", user_id="USER_ID", device_id="DEVICE_ID", event_properties={ "source": "notification" } )) ``` ## User properties User properties describe your users, such as device details, preferences, or language. Set them to understand who performs an action in your app. The Identify call sets a user's properties without sending an event. The SDK supports the operations `set`, `set_once`, `unset`, `add`, `append`, `prepend`, `pre_insert`, `post_insert`, `remove`, and `clear_all` on individual user properties. Declare the operations through the Identify interface. Chain multiple operations together in a single Identify object, then pass it to the Amplitude client to send to the server. > **Note:** > > If you send the Identify call after the event, the operation results appear immediately in the dashboard user's profile area. The results don't appear in chart results until another event sends after the Identify call. The Identify call only affects events going forward. For more details, refer to [user properties and events](https://amplitude.com/docs/data/user-properties-and-events). ### Set a user property To set a user property: instantiate an Identify object, call Identify methods on it, then pass the object to the client. ```Python from amplitude import Identify, EventOptions identify_obj=Identify() client.identify(identify_obj, EventOptions(user_id="USER_ID")) ``` #### Identify.set Sets the value of a user property. For example, set a user's role. ```Python from amplitude import Identify, EventOptions identify_obj=Identify() identify_obj.set("location", "LAX") client.identify(identify_obj, EventOptions(user_id="USER_ID")) ``` #### Identify.set\_once Increments a user property by a numerical value. If the user property doesn't have a value yet, the SDK initializes it to 0 before incrementing. For example, track a user's travel count. ```Python from amplitude import Identify, EventOptions identify_obj=Identify() identify_obj.add("travel-count", 1) client.identify(identify_obj, EventOptions(user_id="USER_ID")) ``` #### Arrays in user properties Use arrays as user properties. Set arrays directly, or use `prepend`, `append`, `pre_insert`, and `post_insert` to build an array. #### Identify.prepend Prepends one or more values to a user property array. If the user property doesn't have a value yet, the SDK initializes it to an empty list before prepending. ```Python from amplitude import Identify, EventOptions identify_obj=Identify() identify_obj.prepend("visited-locations", "LAX") client.identify(identify_obj, EventOptions(user_id="USER_ID")) ``` #### Identify.append Appends one or more values to a user property array. If the user property doesn't have a value yet, the SDK initializes it to an empty list before appending. ```Python from amplitude import Identify, EventOptions identify_obj=Identify() identify_obj.append("visited-locations", "SFO") client.identify(identify_obj, EventOptions(user_id="USER_ID")) ``` #### Identify.pre\_insert Inserts one or more values at the beginning of a user property array, only if those values don't exist in the array yet. If the user property doesn't have a value yet, the SDK initializes it to an empty list before inserting. If the user property already has the value, the operation is a no-op. ```Python from amplitude import Identify, EventOptions identify_obj=Identify() identify_obj.pre_insert("unique-locations", "LAX") client.identify(identify_obj, EventOptions(user_id="USER_ID")) ``` #### Identify.post\_insert Inserts one or more values at the end of a user property array, only if those values don't exist in the array yet. If the user property doesn't have a value yet, the SDK initializes it to an empty list before inserting. If the user property already has the value, the operation is a no-op. ```Python from amplitude import Identify, EventOptions identify_obj=Identify() identify_obj.post_insert("unique-locations", "SFO") client.identify(identify_obj, EventOptions(user_id="USER_ID")) ``` #### Identify.remove Removes one or more values from a user property array if they exist. If the value doesn't exist in the user property, the operation is a no-op. ```Python from amplitude import Identify, EventOptions identify_obj=Identify() identify_obj.remove("unique-locations", "JFK") client.identify(identify_obj, EventOptions(user_id="USER_ID")) ``` #### Identify.clear\_all Removes all user properties from a user. Use `clear_all` with care because the operation is irreversible. ```Python from amplitude import Identify, EventOptions identify_obj=Identify() identify_obj.clear_all() client.identify(identify_obj, EventOptions(user_id="USER_ID")) ``` ## User groups Amplitude supports assigning users to groups and running queries such as Count by Distinct on those groups. For example, group users by organization with an `orgId`: assign Joe to `orgId` `10` and Sue to `orgId` `15`. In the Event Segmentation chart, select "..performed by" `orgId` to query the number of organizations that performed a specific event. Amplitude includes a group in the count when at least one member performed the event. When you set groups, define a `group_type` and `group_name`. In the previous example, `orgId` is the `group_type`, and `10` and `15` are each a `group_name`. Another example uses `sport` as the `group_type` with `group_name` values like `tennis` and `baseball`. Use `set_group()` to designate which groups a user belongs to. This also sets `group_type:group_name` as a user property. The call overwrites any existing `group_name` value for that user's `group_type`, along with the corresponding user property value. `group_type` is a string. `group_name` can be a string or an array of strings to indicate that a user belongs to multiple groups. For example, if Joe is in `orgId` `10` and `16`, the `group_name` is `[10, 16]`. ```Python # set group with single group name client.set_group(group_type="org_id", group_name="15", event_options=EventOptions(user_id="USER_ID")) # set group with multiple group names client.set_group(group_type="org_id", group_name=["15", "21"], event_options=EventOptions(user_id="USER_ID")) ``` Set event-level groups with the `groups` attribute of events. ```Python # set groups when initial a event instance event = BaseEvent("event_type", "user_id", groups={"org_id": ["15", "21"]}) # set groups for an existing instance event["groups"] = {"sport": "soccer"} client.track(event) ``` ## Group properties Use the Group Identify API to set or update the properties of specific groups. These updates only affect events going forward. The `group_identify()` method accepts a group type string, a group name string, and an Identify object to apply to the group. ```Python identify_obj=Identify() identify_obj.set("locale", "en-us") client.group_identify(group_type="org-id", group_name="15", identify_obj=identify_obj) ``` ## Track revenue To track revenue for a user, use `revenue()` with the Revenue interface. Revenue instances store each transaction and let you define special revenue properties such as `revenue_type` and `product_id`. Amplitude's Event Segmentation and Revenue LTV charts use these properties. Pass Revenue instance objects into `revenue` to send them as revenue events to Amplitude. Amplitude then displays revenue data automatically. Use this approach to track both in-app and non-in-app purchases. To track revenue from a user, call `revenue` each time a user generates revenue. For example, a user purchases 3 units of a product at 3.99 each. ```Python from amplitude import Revenue revenue_obj = Revenue(price=3.99, quantity=3, product_id="com.company.productId") client.revenue(revenue_obj, EventOptions(user_id="USER_ID")) ``` ### The revenue interface | Name | Type | Description | Default | | --- | --- | --- | --- | | `product_id` (optional) | string | An identifier for the product. Amplitude recommends something like the Google Play Store product ID. | null | | quantity _(required)_ | int | The quantity of products purchased. `revenue = quantity * price` | 1 | | price _(required)_ | Double | The price of the products purchased, and this can be negative. `revenue = quantity * price` | null | | `revenue_type` (optional, _required for revenue verification_) | String | The revenue type (for example, tax, refund, income). | null | | receipt (optional) | String | The receipt identifier of the revenue. | null | | `receipt_sig` (optional, _required for revenue verification_) | String | The receipt signature of the revenue. | null | | properties (optional) | JSONObject | An object of event properties to include in the revenue event. | null | ## Flush The `flush` method triggers the client to send buffered events. ```py client.flush() ``` ## Add The `add` method adds a plugin to the Amplitude client instance. Plugins help process and send events. [Learn more about plugins](#plugins). ```py client.add(plugin_obj) ``` ## Remove The `remove` method removes the given plugin from the client instance if it exists. ```py client.remove(plugin_obj) ``` ## Shutdown Use the `shutdown` method to close the instance. A closed instance doesn't accept new events and tries to flush events left in the buffer. After flushing, the client instance shuts down running threads. In version v1.1.1 and higher, the SDK automatically registers the `shutdown` method to run when the main thread exits. ```py client.shutdown() ``` ## Plugins Plugins extend the Amplitude SDK's behavior. For example, modify event properties (enrichment type) or send data to third-party APIs (destination type). A plugin is an object with the methods `setup()` and `execute()`. ### Plugin.setup Prepares the plugin for use. Takes a `client` instance as a parameter and returns `None`. Typical use: copy configuration from `client.configuration` or instantiate plugin dependencies. The SDK calls this method when you register the plugin through `client.add()`. ### Plugin.execute Processes events. Takes an `event` instance as a parameter. For an enrichment plugin, returns the modified or enriched event. For a destination plugin, returns a map with the keys `event` (BaseEvent), `code` (number), and `message` (string). The SDK calls this method for each event instrumented through the client interface, including Identify, GroupIdentify, and Revenue events. ### Plugin examples #### Enrichment type plugin This example plugin modifies each instrumented event by adding an increment integer to the event's `event_id` property. ```py from threading import Lock from amplitude import Amplitude, EventPlugin, PluginType class AddEventIdPlugin(EventPlugin): def __init__(self, start=0): super().__init__(PluginType.ENRICHMENT) self.current_id = start self.configuration = None self.lock = Lock() def setup(self, client): self.configuration = client.configuration def execute(self, event): with self.lock: event.event_id = self.current_id self.current_id += 1 return event client = Amplitude(AMPLITUDE_API_KEY) client.add(AddInsertIdPlugin()) ``` #### Destination type plugin ```Python from amplitude import Amplitude, EventPlugin, DestinationPlugin, PluginType import requests class MyDestinationPlugin(DestinationPlugin): def __init__(self): super().__init__() # other init operations self.url = "api endpoint url" self.configuration = None def setup(self, client): # setup plugin using client instance # triggered by client.add() method super().setup(client) self.configuration = client.configuration def execute(self, event): # process event using plugins in this destination plugin instance event = self.timeline.process(event) # send event to customized destination payload = '{"key":"secret", "event": ' + str(event) + '}' requests.post(self.url, data=payload) self.configuration.logger.info("Event sent") client = Amplitude(AMPLITUDE_API_KEY) client.add(MyDestinationPlugin()) ``` ================================================================================ # iOS Swift SDK URL: https://amplitude.com/docs/sdks/analytics/ios/ios-swift-sdk ================================================================================ # iOS Swift SDK - **Repository:** [Amplitude-Swift](https://github.com/amplitude/Amplitude-Swift) This is the official documentation for the Amplitude Analytics iOS SDK. > **Info:** Unified SDK > > Install the [Unified SDK for Swift](https://amplitude.com/docs/sdks/analytics/ios/unified-sdk) to access the Experiment SDK along with other Amplitude products (Analytics, Session Replay). The Unified SDK provides a single entry point for all Amplitude features and handles the initialization and configuration of all components. ## Install the SDK #### Swift Package Manager 1. Navigate to _File > Swift Package Manager > Add Package Dependency_. 2. Enter the URL `https://github.com/amplitude/Amplitude-Swift` in the search bar. 3. Select a specific version or let Xcode resolve to the latest version automatically. 4. Select **Next** to confirm the addition of the package as a dependency. 5. Build your project to confirm the package integrates correctly. #### CocoaPods 6. Add the dependency to your `Podfile`: ```bash pod 'AmplitudeSwift', '~> 1.0' ``` 7. Run `pod install` in the project directory. #### Carthage Add the following line to your `Cartfile`. ```bash github "amplitude/Amplitude-Swift" ~> 1.0 ``` Go to the [Carthage docs](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application) for more information. ## Initialize the SDK Initialize the SDK before you instrument events. You need the API key for your Amplitude project. #### Swift ```swift let amplitude = Amplitude(configuration: Configuration( apiKey: AMPLITUDE_API_KEY, autocapture: [ .sessions, .appLifecycles, .screenViews, .elementInteractions, .networkTracking, .frustrationInteractions ] )) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY]; configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[ AMPAutocaptureOptions.sessions, AMPAutocaptureOptions.appLifecycles, AMPAutocaptureOptions.screenViews, AMPAutocaptureOptions.elementInteractions, AMPAutocaptureOptions.networkTracking, AMPAutocaptureOptions.frustrationInteractions ]]; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` ## Configure the SDK #### Configuration options | Name | Description | Default Value | | --- | --- | --- | | `apiKey` | The API key of your project. This parameter is required. | n/a | | `instanceName` | The name of the instance. Instances with the same name share storage and identity. For isolated storage and identity, use a unique `instanceName` for each instance. | `$default_instance` | | `storageProvider` | Implements a custom `storageProvider` class from `Storage`. Not supported in Objective-C. | `PersistentStorage` | | `identifyStorageProvider` | Implements a custom `Storage` for intercepted Identify events. Not supported in Objective-C. | `PersistentStorage` | | `logLevel` | The log level enums: `LogLevelEnum.off`, `LogLevelEnum.error`, `LogLevelEnum.warn`, `LogLevelEnum.log`, `LogLevelEnum.debug`. | `LogLevelEnum.warn` | | `loggerProvider` | Implements a custom `loggerProvider` class from the Logger, and passes it in the configuration during initialization to help collect error messages from the SDK in a production environment. | `ConsoleLogger` | | `flushIntervalMillis` | The amount of time the SDK waits before it uploads unsent events to the server, or before it reaches the `flushQueueSize` threshold. | `30000` | | `flushQueueSize` | The SDK uploads events when the unsent event count exceeds this threshold, or when it reaches the `flushIntervalMillis` interval. | `30` | | `flushMaxRetries` | Maximum retry times. | `6` | | `minIdLength` | The minimum length for user id or device id. When unset, the server enforces a minimum of 5 characters. | `nil` | | `partnerId` | The partner id for partner integration. | `nil` | | `identifyBatchIntervalMillis` | The amount of time the SDK batches intercepted identify events. | `30000` | | `flushEventsOnClose` | Flushes unsent events on app close. | `true` | | `callback` | Callback function after event sent. | `nil` | | `optOut` | Opt the user out of tracking. | `false` | | ~`defaultTracking`~ (Deprecated. Use [`autocapture`](#autocapture) instead.) | Enable tracking of default events for sessions, app lifecycles, and screen views. | `DefaultTrackingOptions(sessions: true)` | | `autocapture` | Enable tracking of [Autocapture events](#autocapture) for sessions, app lifecycles, screen views, network requests, and element interactions. | `AutocaptureOptions.sessions` | | `enableAutoCaptureRemoteConfig` | Enable remote configuration for autocapture settings. When enabled, Amplitude updates Autocapture settings remotely after initialization. | `true` | | `minTimeBetweenSessionsMillis` | The amount of time for session timeout. | `300000` | | `serverUrl` | An optional custom URL for event uploads. When `nil`, the SDK uses the default endpoint for `serverZone`. | `nil` | | `serverZone` | The server zone to send to. Amplitude adjusts the server url based on this config. | `US` | | `useBatch` | Whether to use batch api. | `false` | | `trackingOptions` | Options to control the values tracked in SDK. | `enable` | | `enableCoppaControl` | Whether to enable COPPA control for tracking options. | `false` | | `migrateLegacyData` | Available in `0.4.7+`. Whether to migrate [maintenance SDK](https://amplitude.com/docs/sdks/analytics/ios/ios-sdk) data (events, user/device ID). | `true` | | `offline` | Available in `1.2.0+`. Whether the SDK connects to a network. Learn more in [Offline mode](#offline-mode). | `false` | | `maxQueuedEventCount` | Available in `1.9.1+`. Maximum number of events to retain in storage. When set to a positive number, the SDK removes oldest events at startup to maintain this limit. When set to -1, no cleanup occurs. | `-1` | | `networkTrackingOptions` | Available in `1.12.0+`. Options to control the network tracking. | `NetworkTrackingOptions.default` | | `interactionsOptions` | Available in `1.15.0+`. Options to control the interaction tracking. | `InteractionsOptions()` | | `enableDiagnostics` | Whether to send SDK diagnostic information to Amplitude to help improve the SDK. | `true` | | `enableRequestBodyCompression` | Whether to gzip the request body. Only applies when you set a custom `serverUrl`; the SDK's default endpoints always compress request bodies. | `false` | | `plan` | Tracking plan information. Set `branch`, `source`, `version`, and `versionId` to tag events with the tracking plan that produced them. | `nil` | | `ingestionMetadata` | Ingestion metadata. Set `sourceName` and `sourceVersion` to identify the upstream source of the events. | `nil` | ## Track events Events represent how users interact with your application. For example, "Button Clicked" may be an action you want to track. #### Swift ```swift let event = BaseEvent( eventType: "Button Clicked", eventProperties: ["my event prop key": "my event prop value"] ) amplitude.track(event: event) ``` #### Obj-C ```objc AMPBaseEvent *event = [AMPBaseEvent initWithEventType:@"Button Clicked" eventProperties:@{@"my event prop key": @"my event prop value"}]; [amplitude track:event]; ``` ## Verify your setup and ingestion > **Tip:** Verify first event ingestion > > The iOS Swift SDK queues events and uploads them every 30 seconds or after 30 events by default, whichever comes first. To check the event immediately, call `amplitude.flush()` after `track()`. > > Set the configuration's `logLevel` to `LogLevelEnum.debug`: > > ```swift > let amplitude = Amplitude(configuration: Configuration( > apiKey: AMPLITUDE_API_KEY, > logLevel: LogLevelEnum.debug > )) > ``` > > In Xcode, open the Console and enter `com.amplitude` in the filter field. Confirm that the SDK queues and uploads the event without an error. > > Open [User Lookup activity](https://amplitude.com/docs/analytics/user-data-lookup#activity), find the event's user or device ID, and enable **Live event updates**. Confirm that the event appears in the activity stream. Another way to instrument a basic tracking event: #### Swift ```swift amplitude.track( eventType: "Button Clicked", eventProperties: ["my event prop key": "my event prop value"] ) ``` #### Obj-C ```objc [amplitude track:@"Button Clicked" eventProperties:@{ @"my event prop key": @"my event prop value" }]; ``` ### Flush queued events Call `flush()` to request an immediate upload of queued events. The SDK performs the upload asynchronously. #### Swift ```swift amplitude.flush() ``` #### Obj-C ```objc [amplitude flush]; ``` ## Identify > **Note:** > > Starting from release v0.4.0, the SDK batches identify events that contain only set operations and sends them with fewer events. This change doesn't affect how the set operations run. The config `identifyBatchIntervalMillis` manages the interval to flush the batched identify intercepts. Identify sets the user properties of a particular user without sending any event. The SDK supports the operations `set`, `setOnce`, `unset`, `add`, `append`, `prepend`, `preInsert`, `postInsert`, `remove`, and `clearAll` on individual user properties. Declare the operations through a provided Identify interface. You can chain multiple operations in a single Identify object. Then pass the Identify object to the Amplitude client to send to the server. > **Note:** > > If you send the Identify call after the event, the operation results appear immediately in the dashboard user's profile area, but don't appear in chart results until you send another event after the Identify call. The Identify call only affects events going forward. For more details, refer to [User properties and events](https://amplitude.com/docs/data/user-properties-and-events). You can handle the identity of a user using the identify methods. Proper use of these methods can connect events to the correct user as they move across devices, browsers, and other platforms. Send an identify call containing those user property operations to Amplitude server to tie a user's events with specific user properties. #### Swift ```swift let identify = Identify() identify.set(property: "color", value: "green") amplitude.identify(identify: identify) ``` #### Obj-C ```objc AMPIdentify *identify = [AMPIdentify new]; [identify set:@"color" value:@"green"]; [amplitude identify:identify]; ``` ### Clear all user properties Use `clearAll` to remove all user properties from a user. Use `clearAll` carefully because the operation is irreversible. #### Swift ```swift let identify = Identify() identify.clearAll() amplitude.identify(identify: identify) ``` #### Obj-C ```objc AMPIdentify *identify = [AMPIdentify new]; [identify clearAll]; [amplitude identify:identify]; ``` ## Autocapture Starting from release v1.8.0, the SDK can track more events without manual instrumentation. Configure the SDK to track the following events automatically: - Sessions - App lifecycles - Screen views - Element interactions - Frustration interactions - Rage clicks - Dead clicks - Network requests #### Autocapture options | Name | Type | Enabled by default | Description | | --- | --- | --- | --- | | `sessions` | `AutocaptureOptions` | Yes | Enables session tracking. When set, Amplitude tracks session start and session end events. Otherwise, Amplitude doesn't track session events. When this setting isn't set, Amplitude tracks `sessionId` only. Refer to [Track sessions](#track-sessions) for more information. | | `appLifecycles` | `AutocaptureOptions` | No | Enables application lifecycle event tracking. When set, Amplitude tracks application installed, application updated, application opened, and application backgrounded events. Event properties tracked include: `[Amplitude] Version`, `[Amplitude] Build`, `[Amplitude] Previous Version`, `[Amplitude] Previous Build`, `[Amplitude] From Background`. Refer to [Track application lifecycles](#track-application-lifecycles) for more information. | | `screenViews` | `AutocaptureOptions` | No | Enables screen view tracking. When set, Amplitude tracks screen viewed events. Event properties tracked include: `[Amplitude] Screen Name`. Refer to [Track screen views](#track-screen-views) for more information. | | `elementInteractions` | `AutocaptureOptions` | No | Enables element interaction tracking. When set, Amplitude tracks user interactions with `UIControl` elements and `UIGestureRecognizer`. Event properties tracked include: `[Amplitude] Action`, `[Amplitude] Target View Class`, `[Amplitude] Target Text`, `[Amplitude] Action Method`, `[Amplitude] Gesture Recognizer`, `[Amplitude] Hierarchy`, `[Amplitude] Accessibility Identifier`, `[Amplitude] Accessibility Label`, `[Amplitude] Screen Name`. Refer to [Track element interactions](#track-element-interactions) for more information. | | `networkTracking` | `AutocaptureOptions` | No | Enables network tracking. When set, Amplitude tracks network requests. Event properties tracked include: `[Amplitude] URL`, `[Amplitude] URL Query`, `[Amplitude] URL Fragment`, `[Amplitude] Request Method`, `[Amplitude] Status Code`, `[Amplitude] Error Code`, `[Amplitude] Error Message`, `[Amplitude] Start Time`, `[Amplitude] End Time`, `[Amplitude] Duration`, `[Amplitude] Request Body Size`, `[Amplitude] Response Body Size`. Refer to [Track network requests](#track-network-requests) for more information. | | `frustrationInteractions` | `AutocaptureOptions` | No | Available in `1.15.0+`. Enables frustration interaction tracking. When set, Amplitude tracks frustration interactions (Rage Clicks and Dead Clicks) with `UIControl` elements and `UIGestureRecognizer`. Rage Clicks generate the `[Amplitude] Rage Click` event and Dead Clicks generate the `[Amplitude] Dead Click` event. Go to [Track frustration interactions](#track-frustration-interactions) for more information. | You can configure Amplitude to start tracking Autocapture events. Otherwise, you can omit the configuration to keep only session tracking enabled. #### Swift The `autocapture` configuration accepts an [`OptionSet`](https://developer.apple.com/documentation/swift/optionset){:target="\_blank"} with `AutocaptureOptions` values. ```swift let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: [.sessions, .appLifecycles, .screenViews, .networkTracking] )) ``` By default, if you don't explicitly set the `autocapture` configuration during `Configuration` initialization, `configuration.autocapture` automatically includes `AutocaptureOptions.sessions`. To prevent automatic session event capture, set `autocapture` without the `AutocaptureOptions.sessions` option. ```swift let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: .appLifecycles // or use `[]` to disable Autocapture. )) ``` #### Obj-C The `autocapture` configuration accepts an `Array` of `AutocaptureOptions` values. ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:@"API_KEY"]; configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[ AMPAutocaptureOptions.sessions, AMPAutocaptureOptions.appLifecycles, AMPAutocaptureOptions.screenViews, AMPAutocaptureOptions.networkTracking ]]; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` By default, if you don't explicitly set the `autocapture` configuration during `Configuration` initialization, `configuration.autocapture` automatically includes `AutocaptureOptions.sessions`. To prevent automatic session event capture, set `autocapture` without the `AutocaptureOptions.sessions` option. ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:@"API_KEY"]; configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[AMPAutocaptureOptions.appLifecycles]]; // or use an empty array to disable Autocapture. Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` ### Remote configuration for autocapture Starting from release v1.10.0, the SDK supports remote configuration for autocapture settings. This feature lets you update autocapture settings after initialization without requiring an app update. By default, Amplitude enables remote configuration for autocapture. To disable it, set `enableAutoCaptureRemoteConfig` to `false` in the configuration: #### Swift ```swift let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: [.sessions, .appLifecycles, .screenViews], enableAutoCaptureRemoteConfig: false )) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:@"API_KEY"]; configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[ AMPAutocaptureOptions.sessions, AMPAutocaptureOptions.appLifecycles, AMPAutocaptureOptions.screenViews ]]; configuration.enableAutoCaptureRemoteConfig = NO; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` When you enable remote configuration, the SDK checks for updates to Autocapture settings in your project. If the SDK finds updates, it applies them automatically. This lets you: - Enable or disable specific autocapture features remotely. - Change autocapture settings without requiring users to update the app. Changes made through remote configuration affect future events and don't apply to events that Amplitude already tracked. ### Track sessions Amplitude enables session tracking by default. Include `AutocaptureOptions.sessions` in the `autocapture` configuration to explicitly configure the SDK to track session events, or to enable session event tracking with other Autocapture configurations. #### Swift ```swift let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: .sessions )) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:@"API_KEY"]; configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[AMPAutocaptureOptions.sessions]]; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` For more information about session tracking, refer to [User sessions](#user-sessions). > **Note:** > > `trackingSessionEvents` is deprecated. Use the `AutocaptureOptions.sessions` option of the `autocapture` configuration instead. ### Track application lifecycles To enable Amplitude to track application lifecycle events, include `AutocaptureOptions.appLifecycles` in the `autocapture` configuration. #### Swift ```swift let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: .appLifecycles )) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:@"API_KEY"]; configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[AMPAutocaptureOptions.appLifecycles]]; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` When you enable this setting, Amplitude tracks the following events: - `[Amplitude] Application Installed`: this event fires when a user opens the application for the first time after installation, by observing the `UIApplicationDidFinishLaunchingNotification` notification internally. - `[Amplitude] Application Updated`: this event fires when a user opens the application after updating the application, by observing the `UIApplicationDidFinishLaunchingNotification` notification internally. - `[Amplitude] Application Opened`: this event fires when a user launches or foregrounds the application after the first open, by observing the `UIApplicationDidFinishLaunchingNotification` or `UIApplicationWillEnterForegroundNotification` notification internally. - `[Amplitude] Application Backgrounded`: this event fires when a user backgrounds the application, by observing the `UIApplicationDidEnterBackgroundNotification` notification internally. ### Track screen views To enable Amplitude to track screen view events, include `AutocaptureOptions.screenViews` in the `autocapture` configuration. > **Warning:** > > This feature supports UIKit. For SwiftUI, track the corresponding event manually. #### Swift ```swift // UIKit let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: .screenViews )) // Swift UI let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: [] )) amplitude.track(event: ScreenViewedEvent(screenName: "Screen Name")) ``` #### Obj-C ```objc // UIKit AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:@"API_KEY"]; configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[AMPAutocaptureOptions.screenViews]]; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; // Swift UI configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[]]; [amplitude track:[AMPScreenViewedEvent initWithScreenName:@"Screen Name"]]; ``` When you enable this setting, Amplitude tracks the `[Amplitude] Screen Viewed` event and sets the screen name property of this event to the name of the top-most view controller's class. Amplitude reads this value from the controller class metadata `viewDidAppear` method swizzling. ### Track network requests To enable Amplitude to track network requests, include `AutocaptureOptions.networkTracking` in the `autocapture` configuration. > **Warning:** > > This feature doesn't work with requests sent by `URLConnection` or on watchOS and iOS 13. #### Swift ```swift let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: .networkTracking )) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:@"API_KEY"]; configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[AMPAutocaptureOptions.networkTracking]]; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` With the default configuration, the SDK tracks network requests from all hosts (except `*.amplitude.com`) with status code `500` to `599`. To customize the tracking behavior, set `Configuration.networkTrackingOptions` with `NetworkTrackingOptions`. #### NetworkTrackingOptions | Name | Description | Default Value | | --- | --- | --- | | `captureRules` | The rules for capturing network requests. Always append rules with specific hosts to the bottom of the list. | `none` | | `ignoreHosts` | The hosts to ignore. Supports wildcard characters `*`. For example, `["*"]` ignores all hosts, and `["*.notmyapi.com", "notmyapi.com"]` ignores `notmyapi.com` and all subdomains. | `[]` | | `ignoreAmplitudeRequests` | Whether to ignore Amplitude requests. | `true` | #### NetworkTrackingOptions.CaptureRule | Name | Description | Default Value | | --- | --- | --- | | `hosts` | The hosts to capture. Supports wildcard characters `*`. For example, `["*"]` matches all hosts, and `["*.example.com", "example.com"]` matches `example.com` and all subdomains. | `none` | | `urls` | Experimental. Available in `1.15.0+`. The URLs to capture. Supports exact match and regex pattern. Includes query parameters and fragment identifier. For example, `URLPattern.exact("https://example.com/api/status")` matches `https://example.com/api/status`, and `URLPattern.regex("https://example.com/api/.*")` matches `https://example.com/api/status` and `https://example.com/api/error`. | `none` | | `statusCodeRange` | The status code range to capture. Supports comma-separated ranges or single status codes. For example, `"0,200-299,413,500-599"`. | `"500-599"` | | `methods` | Experimental. Available in `1.15.0+`. The HTTP methods to capture. Use `*` to match all methods. For example, `["POST", "PUT", "DELETE"]`. | `["*"]` | | `requestHeaders` | Available in `1.15.0+`. Captures request headers. | `nil` | | `responseHeaders` | Available in `1.15.0+`. Captures response headers. | `nil` | | `requestBody` | Available in `1.15.0+`. Captures fields in the request body (go to #CaptureBody). | `nil` | | `responseBody` | Available in `1.15.0+`. Captures fields in the response body (go to #CaptureBody). | `nil` | #### NetworkTrackingOptions.CaptureHeader | Name | Description | Default Value | | --- | --- | --- | | `allowlist` | Available in `1.15.0+`. The headers to capture. Case-insensitive. | `[]` | | `captureSafeHeaders` | Available in `1.15.0+`. Whether to capture safe headers. | `true` | > **Note:** > > Amplitude considers `authorization`, `cookie`, and `proxy-authorization` headers sensitive and excludes them even when set to `allowlist`. #### Safe headers list - `access-control-allow-origin` - `access-control-allow-credentials` - `access-control-expose-headers` - `access-control-max-age` - `access-control-allow-methods` - `access-control-allow-headers` - `accept-patch` - `accept-ranges` - `age` - `allow` - `alt-svc` - `cache-control` - `connection` - `content-disposition` - `content-encoding` - `content-language` - `content-length` - `content-location` - `content-md5` - `content-range` - `content-type` - `date` - `delta-base` - `etag` - `expires` - `im` - `last-modified` - `link` - `location` - `permanent` - `p3p` - `pragma` - `proxy-authenticate` - `public-key-pins` - `retry-after` - `server` - `status` - `strict-transport-security` - `trailer` - `transfer-encoding` - `tk` - `upgrade` - `vary` - `via` - `warning` - `www-authenticate` - `x-b3-traceid` - `x-frame-options` #### NetworkTrackingOptions.CaptureBody | Name | Description | Default Value | | --- | --- | --- | | `allowlist` | Available in `1.15.0+`. The fields to capture. Case-sensitive. Supports wildcards: `*` matches one level of field, `**` matches any number of levels of fields. | `[]` | | `excludelist` | Available in `1.15.0+`. The fields to exclude from capture. Case-sensitive. Supports wildcards: `*` matches one level of field, `**` matches any number of levels of fields. | `[]` | > **Note:** > > - The `captureRules` and `ignoreHosts` properties are mutually exclusive. If you set both, `ignoreHosts` takes precedence. > - Amplitude matches incoming requests against the `captureRules` from bottom to top. For example, for the following configuration: > > ```swift > captureRules: [ > .init(hosts: ["*"], statusCodeRange: "400-499,500-599"), > .init(hosts: ["*.example.com", "example.com"], statusCodeRange: "0,500-599"), > ] > ``` > > With the above configuration, the SDK processes the following requests: > > - A request to `example.com` with response code 503: matches last rule's hosts, matches `statusCodeRange` filter, captured. > - A request to `example.com` with response code 401: matches last rule's hosts, doesn't match `statusCodeRange` filter, ignored. > - A request to `notmyapi.com` with response code 401: doesn't match last rule's hosts, matches first rule's hosts, matches `statusCodeRange` filter, captured. > - A request to `notmyapi.com` with response code 200: doesn't match last rule's hosts, matches first rule's hosts, doesn't match `statusCodeRange` filter, ignored. The default configuration tracks all hosts except `*.amplitude.com` with status code `500` to `599`. #### NetworkTrackingOptions.default | Name | Description | Value | | --- | --- | --- | | `captureRules` | Captures all hosts (except `*.amplitude.com`) with status code 500 to 599. | `[AMPNetworkTrackingCaptureRule(hosts: ["*"], statusCodeRange: "500-599")]` | | `ignoreHosts` | Don't ignore any other hosts by default. | `[]` | | `ignoreAmplitudeRequests` | Don't capture Amplitude requests by default. | `true` | Example use: #### Swift ```swift // Style 1: Use the default configuration and append a new rule let networkTrackingOptions = NetworkTrackingOptions.default // contain a rule for all hosts, statusCodeRange: "500-599" networkTrackingOptions.captureRules.append( .init(hosts: ["*.example.com", "example.com"], statusCodeRange: "0,500-599") ) networkTrackingOptions.ignoreHosts.append("notmyapi.com") let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: .networkTracking, networkTrackingOptions: networkTrackingOptions, )) // Style 2: Create a new configuration with a custom rule let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: .networkTracking, networkTrackingOptions: .init( captureRules: [ .init(hosts: ["*"]), // all hosts, statusCodeRange: "500-599" .init(hosts: ["*.example.com", "example.com"], statusCodeRange: "0,400-599"), ], ignoreHosts: ["notmyapi.com"] ), )) ``` #### Obj-C ```objc // Style 1: Use the default configuration and append a new rule AMPNetworkTrackingOptions *networkTrackingOptions = AMPNetworkTrackingOptions.defaultOptions; // contain a rule for all hosts, statusCodeRange: "500-599" NSMutableArray *rules = [networkTrackingOptions.captureRules mutableCopy]; [rules addObject:[[AMPNetworkTrackingCaptureRule alloc] initWithHosts:@[@"*.example.com", @"example.com"] statusCodeRange:@"0,400-599"]]; networkTrackingOptions.captureRules = rules; // Style 2: Create a new configuration with a custom rule NSArray *rules = @[ [[AMPNetworkTrackingCaptureRule alloc] initWithHosts: @[@"*"] statusCodeRange:@"500-599"], [[AMPNetworkTrackingCaptureRule alloc] initWithHosts: @[@"*.example.com", @"example.com"] statusCodeRange:@"0,400-599"] ]; AMPNetworkTrackingOptions *networkTrackingOptions = [[AMPNetworkTrackingOptions alloc] initWithCaptureRules:rules ignoreHosts:@[@"notmyapi.com"] ignoreAmplitudeRequests:true]; // Then use the configuration to initialize the Amplitude instance AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:@"API_KEY"]; configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[AMPAutocaptureOptions.networkTracking]]; configuration.networkTrackingOptions = networkTrackingOptions; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` Header and body capture is generally available in `1.18.0+`. To capture request headers, response headers, and body fields, configure those properties in a `CaptureRule`: #### Swift ```swift let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: .networkTracking, networkTrackingOptions: .init( captureRules: [ .init( hosts: ["*.example.com", "example.com"], statusCodeRange: "0,500-599", requestHeaders: .init(allowlist: ["X-Request-ID"]), responseHeaders: .init(allowlist: ["Content-Type"]), requestBody: .init(allowlist: ["user/*", "product/**/id"]), responseBody: .init(allowlist: ["data/**"], excludelist: ["**/password"]) ), ] ), )) ``` When you enable this setting, Amplitude tracks the `[Amplitude] Network Request` event whenever the application makes a network request. The SDK swizzles URL loading system methods to instrument network activity. #### Event Properties Descriptions | Event property | Description | | --- | --- | | `[Amplitude] URL` | The URL of the network request with sensitive information masked. | | `[Amplitude] URL Query` | The query parameters of the URL. | | `[Amplitude] URL Fragment` | The fragment identifier of the URL. | | `[Amplitude] Request Method` | The HTTP method used for the request (GET, POST, and so forth). | | `[Amplitude] Status Code` | The HTTP status code of the response. | | `[Amplitude] Error Code` | The local error code if the request failed with out a status code. | | `[Amplitude] Error Message` | The local error message if the request failed with out a status code. | | `[Amplitude] Start Time` | The timestamp when the request started, in milliseconds since Unix epoch. | | `[Amplitude] Completion Time` | The timestamp when the request completed, in milliseconds since Unix epoch. | | `[Amplitude] Duration` | The duration of the request in milliseconds. | | `[Amplitude] Request Body Size` | The size of the request body in bytes. | | `[Amplitude] Response Body Size` | The size of the response body in bytes. | | `[Amplitude] Request Body` | The captured stringified JSON request body (when you configure a `requestBody` capture rule). | | `[Amplitude] Response Body` | The captured stringified JSON response body (when you configure a `responseBody` capture rule). | | `[Amplitude] Request Headers` | The captured request headers (when you configure a `requestHeaders` capture rule). | | `[Amplitude] Response Headers` | The captured response headers (when you configure a `responseHeaders` capture rule). | > **Info:** > > For security purposes, the SDK automatically masks sensitive information in the URL, such as usernames and passwords. ### Track deep links Deep link tracking isn't automated. To track deep links, track the corresponding events. #### Swift ```swift let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY" )) if let url = URL(string: "myapp://example/path") { amplitude.track(event: DeepLinkOpenedEvent(url: url)) } amplitude.track(event: DeepLinkOpenedEvent(url: "myapp://example/path", referrer: "https://example.com")) amplitude.track(event: DeepLinkOpenedEvent(activity: activity)) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:@"API_KEY"]; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; [amplitude track:[AMPDeepLinkOpenedEvent initWithUrl:@"url"]]; [amplitude track:[AMPDeepLinkOpenedEvent initWithUrl:@"url" referrer:@"referrer"]]; [amplitude track:[AMPDeepLinkOpenedEvent initWithActivity:activity]]; ``` Amplitude tracks the `[Amplitude] Deep Link Opened` event with the URL and referrer information. ### Track element interactions Amplitude can track user interactions with `UIControl` elements and `UIGestureRecognizer` objects in `UIKit` applications. To enable this option, include `AutocaptureOptions.elementInteractions` in the `autocapture` configuration. > **Note:** > > The `AutocaptureOptions.elementInteractions` option offers an early release version for early feedback. Share your thoughts on the Amplitude [GitHub](https://github.com/amplitude/Amplitude-Swift). #### Swift ```swift let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: .elementInteractions )) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:@"API_KEY"]; configuration.autocapture = [[AMPAutocaptureOptions alloc] initWithOptionsToUnion:@[AMPAutocaptureOptions.elementInteractions]]; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` After you enable this setting, Amplitude tracks the `[Amplitude] Element Interacted` event whenever a user interacts with an element in the application. The SDK swizzles the `UIApplication.sendAction(_:to:from:for:)` method and the `UIGestureRecognizer.state` property setter to instrument `UIControl` action methods and `UIGestureRecognizer` within the application, respectively. #### Event Properties Descriptions | Event property | Description | | --- | --- | | `[Amplitude] Action` | The action that triggered the event. Defaults to `touch`. | | `[Amplitude] Target View Class` | The name of the target view class. | | `[Amplitude] Target Text` | The title of the target `UIControl` element. | | `[Amplitude] Target Accessibility Label` | The accessibility label of the target element. | | `[Amplitude] Target Accessibility Identifier` | The accessibility identifier of the target element. | | `[Amplitude] Action Method` | The name of the function or method that triggers when the interaction occurs. | | `[Amplitude] Gesture Recognizer` | The name of the `UIGestureRecognizer` class that recognizes the interaction. | | `[Amplitude] Hierarchy` | A nested hierarchy of the target view's class inheritance, from the most specific to the most general. | | `[Amplitude] Screen Name` | Refer to [Track screen views](#track-screen-views). | > **Info:** > > Amplitude doesn't support tracking user interactions with UI elements in SwiftUI. ### Track frustration interactions Available in version `1.15.0+`. Amplitude can track frustration interactions (Rage Clicks and Dead Clicks) with `UIControl` elements and `UIGestureRecognizer` objects in `UIKit` applications. To enable this option, include `AutocaptureOptions.frustrationInteractions` in the `autocapture` configuration. #### Swift ```swift let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: .frustrationInteractions )) ``` The `interactionsOptions` configuration accepts an `InteractionsOptions` object to configure the options for capturing rage clicks and dead clicks. #### InteractionsOptions | Name | Description | Default Value | | --- | --- | --- | | `rageClick` | The options for capturing rage clicks. | `RageClickOptions()` | | `rageClick.enabled` | Whether to capture rage clicks. | `true` | | `deadClick` | The options for capturing dead clicks. | `DeadClickOptions()` | | `deadClick.enabled` | Whether to capture dead clicks. | `true` | #### Swift ```swift let amplitude = Amplitude(configuration: Configuration( apiKey: "API_KEY", autocapture: .frustrationInteractions, interactionsOptions: .init( rageClick: .init(enabled: true), deadClick: .init(enabled: true) ) )) ``` Rage Click is a user interaction that occurs four (4) or more times in 1 second on the same element and the distance between each adjacent click is no more than 50 points. When a Rage Click occurs, Amplitude tracks the `[Amplitude] Rage Click` event. #### Event Properties Descriptions | Event property | Description | | --- | --- | | `[Amplitude] Begin Time` | The timestamp when the interaction began in ISO 8601 format. | | `[Amplitude] End Time` | The timestamp when the interaction ended in ISO 8601 format. | | `[Amplitude] Duration` | The duration of the interaction in milliseconds. | | `[Amplitude] Click Count` | The number of clicks that occurred. | | `[Amplitude] Clicks` | The array of clicks that occurred. | | `[Amplitude] Clicks[].X` | The x-coordinate of the click from the top-left corner of the screen. | | `[Amplitude] Clicks[].Y` | The y-coordinate of the click from the top-left corner of the screen. | | `[Amplitude] Clicks[].Time` | The timestamp of the click in ISO 8601 format. | | `[Amplitude] Action` | The action that triggered the event. Defaults to `touch`. | | `[Amplitude] Target View Class` | The name of the target view class. | | `[Amplitude] Target Text` | The title of the target `UIControl` element. | | `[Amplitude] Target Accessibility Label` | The accessibility label of the target element. | | `[Amplitude] Target Accessibility Identifier` | The accessibility identifier of the target element. | | `[Amplitude] Action Method` | The name of the function or method that triggers when the interaction occurs. | | `[Amplitude] Gesture Recognizer` | The name of the `UIGestureRecognizer` class that recognizes the interaction. | | `[Amplitude] Hierarchy` | A nested hierarchy of the target view's class inheritance, from the most specific to the most general. | | `[Amplitude] Screen Name` | Go to [Track screen views](#track-screen-views). | Dead Click is a tap on an interactive element that results in no visible change in the following three (3) seconds. When a Dead Click occurs, Amplitude tracks the `[Amplitude] Dead Click` event. > **Note:** Requirements > > Dead clicks requires the Amplitude Session Replay iOS Plugin version `0.5.0` or higher installed and running. Go to [Session Replay iOS Plugin](https://amplitude.com/docs/sdks/session-replay/session-replay-ios-plugin) for more information. #### Event Properties Descriptions | Event property | Description | | --- | --- | | `[Amplitude] X` | The x-coordinate of the click from the top-left corner of the screen. | | `[Amplitude] Y` | The y-coordinate of the click from the top-left corner of the screen. | | `[Amplitude] Action` | The action that triggered the event. Defaults to `touch`. | | `[Amplitude] Target View Class` | The name of the target view class. | | `[Amplitude] Target Text` | The title of the target `UIControl` element. | | `[Amplitude] Target Accessibility Label` | The accessibility label of the target element. | | `[Amplitude] Target Accessibility Identifier` | The accessibility identifier of the target element. | | `[Amplitude] Action Method` | The name of the function or method that triggers when the interaction occurs. | | `[Amplitude] Gesture Recognizer` | The name of the `UIGestureRecognizer` class that recognizes the interaction. | | `[Amplitude] Hierarchy` | A nested hierarchy of the target view's class inheritance, from the most specific to the most general. | | `[Amplitude] Screen Name` | Go to [Track screen views](#track-screen-views). | #### Ignore a view To exclude a specific `UIView` from rage-click and dead-click detection, call `amp_ignoreInteractionEvent(rageClick:deadClick:)` on the view. Both parameters default to `true`. This method applies to UIKit views only. #### Swift ```swift // Ignore both rage clicks and dead clicks on this view. myView.amp_ignoreInteractionEvent() // Or ignore only dead clicks. myView.amp_ignoreInteractionEvent(rageClick: false, deadClick: true) ``` #### Obj-C ```objc // Ignore both rage clicks and dead clicks on this view. [myView amp_ignoreInteractionEventWithRageClick:YES deadClick:YES]; ``` ## User groups Amplitude supports assigning users to groups and running queries, such as Count by Distinct, on those groups. If at least one group member performed the specific event, 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 you set 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` accepts either a string or an array of strings to indicate that a user is in multiple groups. > **Example:** > > If Joe is in 'orgId' '15', then the `groupName` is '15'. > > #### Swift > > ```swift > // set group with a single group name > amplitude.setGroup(groupType: "orgId", groupName: "15") > ``` > > #### Obj-C > > ```objc > // set group with a single group name > [amplitude setGroup:@"orgId" groupName:@"15"]; > ``` > > If Joe is in 'orgId' 'sport', then the `groupName` is '\["tennis", "soccer"\]'. > > #### Swift > > ```swift > // set group with multiple group names > amplitude.setGroup(groupType: "sport", groupName: ["tennis", "soccer"]) > ``` > > #### Obj-C > > ```objc > // set group with multiple group names > [amplitude setGroup:@"sport" groupNames:@[@"tennis", @"soccer"]]; > ``` You can also set event-level groups by passing an `Event` Object with `groups` to `track`. With event-level groups, the group designation applies only to the specific event you log, and doesn't persist on the user unless you explicitly set it with `setGroup`. #### Swift ```swift amplitude.track( event: BaseEvent( eventType: "event type", eventProperties: [ "eventPropertyKey": "eventPropertyValue" ], groups: ["orgId": "15"] ) ) ``` #### Obj-C ```objc AMPBaseEvent *event = [AMPBaseEvent initWithEventType:@"event type" eventProperties:@{@"eventPropertyKey": @"eventPropertyValue"}]; [event.groups set:@"orgId" value:@"15"]; [amplitude track:event]; ``` ## Group identify Use the Group Identify API to set or update the properties of particular groups. Note these considerations: - Updates affect only future events, and don't update historical events. - You can track up to 5 unique group types and 10 total groups. The `groupIdentify` method accepts a group type string parameter, a group name object parameter, and an Identify object that Amplitude applies to the group. #### Swift ```swift let groupType = "plan" let groupName = "enterprise" let identify = Identify().set(property: "key", value: "value") amplitude.groupIdentify(groupType: groupType, groupName: groupProperty, identify: identify) ``` #### Obj-C ```objc NSString *groupType = @"plan"; NSString *groupName = @"enterprise"; AMPIdentify *identify = [AMPIdentify new]; [identify set:@"key" value:@"value"]; [amplitude groupIdentify:groupType groupName:groupName identify:identify]; ``` ## Track revenue Amplitude can track revenue generated by a user. Amplitude tracks revenue through distinct revenue objects, which have special fields used in Amplitude's Event Segmentation and Revenue LTV charts. This lets Amplitude automatically display data relevant to revenue in the platform. Revenue objects support the following special properties, as well as user-defined properties through the `eventProperties` field. #### Swift ```swift let revenue = Revenue() revenue.price = 3.99 revenue.quantity = 3 revenue.productId = "com.company.productId" amplitude.revenue(revenue: revenue) ``` #### Obj-C ```objc AMPRevenue *revenue = [AMPRevenue new]; revenue.price = 3.99; revenue.quantity = 3; revenue.productId = @"com.company.productId"; [amplitude revenue:revenue]; ``` | Name | Description | | --- | --- | | `productId` | Optional. String. An identifier for the product. Amplitude recommends something like the Google Play Store product ID. Defaults to `null`. | | `quantity` | Required. Integer. The quantity of products purchased. Note: revenue = quantity \* price. Defaults to 1 | | `price` | Required. Double. The price of the products purchased, and this can be negative. Note: revenue = quantity \* price. Defaults to `null`. | | `revenueType` | Optional, but required for revenue verification. String. The revenue type (for example, tax, refund, income). Defaults to `null`. | | `receipt` | Optional. String. The receipt identifier of the revenue. For example, "123456". Defaults to `null`. | | `receiptSignature` | Optional, but required for revenue verification. String. Defaults to `null`. | ## Custom user ID If your app has its own login system that you want to track users with, you can call `setUserId` at any time. #### Swift ```swift amplitude.setUserId(userId: "user@amplitude.com") ``` #### Obj-C ```objc [amplitude setUserId:@"user@amplitude.com"]; ``` Use the helper method `getUserId()` to get the value of the current `userId`. #### Swift ```swift let userId = amplitude.getUserId() ``` #### Obj-C ```objc NSString *userId = [amplitude getUserId]; ``` ## Custom device ID You can assign a new device ID using `deviceId`. When you set a custom device ID, make sure the value is sufficiently unique. Amplitude recommends using a UUID. #### Swift ```swift amplitude.setDeviceId(deviceId: NSUUID().uuidString) ``` #### Obj-C ```objc [amplitude setDeviceId:[[NSUUID UUID] UUIDString]]; ``` ## Custom storage > **Warning:** Swift only > > This feature supports Swift, but not Objective C To store data outside the Amplitude-defined location, customize your own storage by implementing the [Storage protocol](https://github.com/amplitude/Amplitude-Swift/blob/211d0c05830fab47e74fa9a053615cf422618a02/Sources/Amplitude/Types.swift#L62-L86) and setting the `storageProvider` in your configuration. Every iOS app gets a slice of storage for itself, which means that you can read and write your app's files there without colliding with other apps. By default, Amplitude uses this file storage and creates an "amplitude" prefixed folder inside the app "Documents" directory. If you need to expose the Documents folder in the native iOS "Files" app and don't want to expose the "amplitude" prefixed folder, you can customize your own storage provider to persist events on initialization. ```swift Amplitude( configuration: Configuration( apiKey: AMPLITUDE_API_KEY, storageProvider: YourOwnStorage() // YourOwnStorage() should implement Storage ) ) ``` ## Reset when the user logs out `reset` is a shortcut to anonymize users after they log out, by: - Setting `userId` to `null`. - Setting `deviceId` to a new value based on current configuration. With an empty `userId` and a completely new `deviceId`, the current user appears as a brand new user in the dashboard. #### Swift ```swift amplitude.reset() ``` #### Obj-C ```objc [amplitude reset]; ``` ## Plugins Plugins let you extend Amplitude SDK's behavior, for example, by modifying event properties (enrichment type) or sending to third-party APIs (destination type). A plugin is an object with methods `setup()` and `execute()`. ### Plugin types The SDK applies plugins to each event in a fixed order: `before` plugins run first, then `enrichment` plugins, then `destination` plugins. Other plugin types, such as `observe`, run outside this pipeline. - A `before` plugin (`PluginType.before`) runs ahead of every enrichment plugin. Use it to set or guard event fields early, before other plugins read them. It has the same shape as an enrichment plugin, with `type` set to `PluginType.before`. - An `enrichment` plugin (`PluginType.enrichment`) modifies or enriches each event as it passes through, such as adding an event property. Go to [Enrichment type plugin example](#enrichment-type-plugin-example). - A `destination` plugin (`PluginType.destination`) sends events to a destination, such as a third-party API, and ends the pipeline. Go to [Destination type plugin example](#destination-type-plugin-example). - An `observe` plugin (`PluginType.observe`) runs outside the event pipeline. Instead of processing events, it reacts to identity changes by overriding `onUserIdChanged`, `onDeviceIdChanged`, `onSessionIdChanged`, and `onOptOutChanged`. The following observe plugin reacts when the user logs in or out: #### Swift ```swift class LoginObserverPlugin: ObservePlugin { override func onUserIdChanged(_ userId: String?) { // React to login or logout. } } amplitude.add(plugin: LoginObserverPlugin()) ``` ### Plugin.setup This method contains logic for preparing the plugin for use and has the `amplitude` instance as a parameter. A typical use for this method is to instantiate plugin dependencies. The SDK calls this method when you register the plugin to the client through `amplitude.add()`. ### Plugin.execute This method contains the logic for processing events and has the `event` instance as a parameter. When used as an enrichment type plugin, the expected return value is the modified or enriched event. When used as a destination type plugin, the expected return value is `null`. The SDK calls this method for each event, including Identify, GroupIdentify, and Revenue events, that you instrument using the client interface. ### Enrichment type plugin example Here's an example of a plugin that modifies each instrumented event by adding an extra event property. #### Swift ```swift class EnrichmentPlugin: Plugin { let type: PluginType var amplitude: Amplitude? init() { self.type = PluginType.enrichment } func setup(amplitude: Amplitude) { self.amplitude = amplitude } func execute(event: BaseEvent?) -> BaseEvent? { event?.sessionId = -1 if event?.eventProperties == nil { event?.eventProperties = [:] } event?.eventProperties?["event prop key"] = "event prop value" return event } } amplitude.add(plugin: EnrichmentPlugin()) ``` #### Obj-C ```objc [amplitude add:[AMPPlugin initWithType:AMPPluginTypeEnrichment execute:^AMPBaseEvent *_Nullable(AMPBaseEvent * _Nonnull event) { event.sessionId = -1; [event.eventProperties set:@"event prop key" value:@"event prop value"]; return event; }]]; ``` ### Destination type plugin example In destination plugins, you can overwrite the `track()`, `identify()`, `groupIdentify()`, `revenue()`, and `flush()` functions. > **Warning:** Objective-C not supported > > Objective-C supports `flush()` and general `execute()` functions. #### Swift ```swift class TestDestinationPlugin: DestinationPlugin { override func track(event: BaseEvent) -> BaseEvent? { return event } override func identify(event: IdentifyEvent) -> IdentifyEvent? { return event } override func groupIdentify(event: GroupIdentifyEvent) -> GroupIdentifyEvent? { return event } override func revenue(event: RevenueEvent) -> RevenueEvent? { return event } override func flush() { } override func setup(amplitude: Amplitude) { self.amplitude = amplitude } override func execute(event: BaseEvent?) -> BaseEvent? { return event } } ``` #### Obj-C ```objc [amplitude add:[AMPPlugin initWithType:AMPPluginTypeDestination execute:^AMPBaseEvent * _Nullable(AMPBaseEvent * _Nonnull event) { if ([event.eventType isEqualToString:@"$identify"]) { // ... } else if ([event.eventType isEqualToString:@"$groupidentify"]) { // ... } else if ([event.eventType isEqualToString:@"revenue_amount"]) { // ... } else { // ... } return nil; } flush:^() { // ... }]]; ``` ### Remove a plugin To stop a plugin from processing events, pass the same plugin instance to `remove(plugin:)`. #### Swift ```swift let plugin = EnrichmentPlugin() amplitude.add(plugin: plugin) // Later, remove it. amplitude.remove(plugin: plugin) ``` #### Obj-C ```objc AMPPlugin *plugin = [AMPPlugin initWithType:AMPPluginTypeEnrichment execute:^AMPBaseEvent *_Nullable(AMPBaseEvent * _Nonnull event) { return event; }]; [amplitude add:plugin]; // Later, remove it. [amplitude remove:plugin]; ``` ## Troubleshooting and debugging Confirm that the configuration and payload are accurate and check for any unusual messages during debugging. If everything appears correct, check the value of `flushQueueSize` or `flushIntervalMillis`. The SDK queues events and sends them in batches by default, so it doesn't dispatch them to the server immediately. Wait for the SDK to send events to the server before checking for them in the charts. ### Log - Set the log level to debug to collect useful information during debugging. - Customize `loggerProvider` with a `Logger` implementation, such as one that sends error messages to your production logging service. ### Plugin Use a Destination Plugin to print the configuration value and event payload before sending them to the server. Set the logLevel to debug, copy the following `TroubleShootingPlugin` into your project, then add the plugin to the Amplitude instance. [SwiftUI TroubleShootingPlugin example](https://github.com/amplitude/Amplitude-Swift/tree/main/Examples/AmplitudeSwiftUIExample/AmplitudeSwiftUIExample/ExamplePlugins/TroubleShootingPlugin.swift). ### Event callback The event callback runs after the SDK sends the event, for both successful and failed events. Use this method to monitor event status and message. For more information, refer to [configuration > callback](#configuration). ## Advanced topics ### User sessions Amplitude starts a session when the app moves into the foreground, or when the SDK tracks an event in the background. A session ends when the app remains in the background longer than `minTimeBetweenSessionsMillis` without tracking any event. A session continues for the entire time the app is in the foreground, whether or not `configuration.defaultTracking` or `configuration.autocapture` enables session tracking. When the app enters the foreground, Amplitude tracks a session start and starts a countdown based on `minTimeBetweenSessionsMillis`. Amplitude extends the session and restarts the countdown any time it tracks a new event. If the countdown expires, Amplitude waits until the next event to track a session end event. Amplitude doesn't set user properties on session events by default. To add these properties, use `identify()` and `setUserId()`. Amplitude aggregates the user property state and associates the user with events based on `device_id` or `user_id`. Because of how Amplitude manages sessions, several scenarios may make events appear missing or session tracking inaccurate even when the SDK works as expected: - If a user doesn't return to the app, Amplitude doesn't track a session end event to correspond with a session start event. - If you track an event in the background, Amplitude may perceive the session length as longer than the time the user spends on the app in the foreground. - If you modify user properties between the last event and the session end event, the session end event reflects the updated user properties, which may differ from other properties associated with events in the same session. To address this, use an enrichment plugin to set `event['$skip_user_properties_sync']` to `true` on the session end event, which prevents Amplitude from synchronizing properties for that specific event. To learn more, refer to [$skip\_user\_properties\_sync](https://amplitude.com/docs/data/converter-configuration-reference#skipuserpropertiessync) in the Converter Configuration Reference article. Amplitude groups events together by session. Events logged within the same session have the same `session_id`. Amplitude handles sessions automatically, so you don't have to manually call `startSession()` or `endSession()`. You can adjust the time window during which Amplitude extends sessions. The default session expiration time is five minutes. Use the helper method `getSessionId` to get the value of the current `sessionId`. #### Swift ```swift let amplitude = Amplitude( configuration: Configuration( apiKey: AMPLITUDE_API_KEY, minTimeBetweenSessionsMillis: 1000 ) ) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY]; configuration.minTimeBetweenSessionsMillis = 1000; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` > **Note:** > > `trackingSessionEvents` is deprecated. Use the `AutocaptureOptions.sessions` option of `autocapture` instead. You can also track events as out-of-session. Out-of-session events have a `sessionId` of `-1` and behave as follows: 1. Aren't part of the current session. 2. Don't extend the current session. 3. Don't start a new session. 4. Don't change the `sessionId` for subsequent events. A potential use case is events tracked from push notifications, which are usually external to the customer's app usage. Set the `sessionId` to `-1` in `EventOptions` to mark an event as out-of-session when you call `track(event, options)` or `identify(identify, options)`. #### Swift ```swift let outOfSessionOptions = EventOptions(sessionId: -1) amplitude.identify( identify: Identify().set(property: "user-prop", value: true), options: outOfSessionOptions ) amplitude.track( event: BaseEvent(eventType: "Button Clicked"), options: outOfSessionOptions ) ``` #### Obj-C ```objc AMPEventOptions *outOfSessionOptions = [AMPEventOptions new]; outOfSessionOptions.sessionId = -1; AMPIdentify *identify = [AMPIdentify new]; [identify set:@"user-prop" value:YES]; [amplitude identify:identify options:outOfSessionOptions]; AMPBaseEvent *event = [AMPBaseEvent initWithEventType:@"Button Clicked"]; [amplitude track:event options:outOfSessionOptions]; ``` To set the session ID manually, call `setSessionId` with a Unix timestamp in milliseconds or a `Date`. A non-negative timestamp starts a new session at that time, and a negative timestamp ends the current session. #### Swift ```swift // Start a new session at the current time. amplitude.setSessionId(timestamp: Int64(Date().timeIntervalSince1970 * 1000)) // Or pass a Date directly. amplitude.setSessionId(date: Date()) ``` #### Obj-C ```objc [amplitude setSessionIdWithTimestamp:(long long)([[NSDate date] timeIntervalSince1970] * 1000)]; // Or pass an NSDate directly. [amplitude setSessionIdWithDate:[NSDate date]]; ``` ### Log level Control the level of logs that print to the developer console. - 'OFF': Suppresses all log messages. - 'ERROR': Shows error messages only. - 'WARN': Shows error messages and warnings. This level logs issues that might be a problem and cause some oddities in the data. For example, this level displays a warning for properties with null values. - 'LOG': Shows informative messages about events. - 'DEBUG': Shows error messages, warnings, and informative messages that may be useful for debugging. Set the log level `logLevel` with the level you want. #### Swift ```swift let amplitude = Amplitude( configuration: Configuration( apiKey: AMPLITUDE_API_KEY, logLevel: LogLevelEnum.log ) ) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY]; configuration.logLevel = AMPLogLevelLOG; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` Amplitude [merges user data](https://amplitude.com/docs/data/sources/instrument-track-unique-users), so any events associated with a known `userId` or `deviceId` link to the existing user. If a user logs out, Amplitude can merge that user's logged-out events with the user's record. You can change this behavior and log those events to an anonymous user instead. To log events to an anonymous user: 1. Set the `userId` to null. 2. Generate a new `deviceId`. Events from the current user or device appear as a new user in Amplitude. Note: If you do this, you can't see that the two users were using the same device. #### Swift ```swift amplitude.reset() ``` #### Obj-C ```objc [amplitude reset]; ``` ### Disable tracking By default, the iOS SDK tracks several user properties such as `carrier`, `city`, `country`, `ip_address`, `language`, and `platform`. Use the provided `TrackingOptions` interface to customize and toggle individual fields. Before you initialize the SDK with your apiKey, create a `TrackingOptions` instance with your configuration and set it on the SDK instance. #### Swift ```swift let trackingOptions = TrackingOptions() trackingOptions.disableTrackCity().disableTrackIpAddress() let amplitude = Amplitude( configuration: Configuration( apiKey: AMPLITUDE_API_KEY, trackingOptions: trackingOptions ) ) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY]; [configuration.trackingOptions disableTrackCity]; [configuration.trackingOptions disableTrackIpAddress]; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` You can individually control tracking for each field, and each has a corresponding method (for example, `disableCountry`, `disableLanguage`). | Method | Description | | --- | --- | | `disableTrackCarrier()` | Disable tracking of device's carrier | | `disableTrackCity()` | Disable tracking of user's city | | `disableTrackCountry()` | Disable tracking of user's country | | `disableTrackDeviceModel()` | Disable tracking of device model | | `disableTrackDeviceManufacturer()` | Disable tracking of device manufacturer | | `disableTrackDMA()` | Disable tracking of user's designated market area (DMA) | | `disableTrackIpAddress()` | Disable tracking of user's IP address | | `disableTrackLanguage()` | Disable tracking of device's language | | `disableTrackIDFV()` | Disable tracking of identifier for vendors (IDFV) | | `disableTrackOsName()` | Disable tracking of device's OS Name | | `disableTrackOsVersion()` | Disable tracking of device's OS Version | | `disableTrackPlatform()` | Disable tracking of device's platform | | `disableTrackRegion()` | Disable tracking of user's region | | `disableTrackVersionName()` | Disable tracking of your app's version name | > **Note:** > > Using `TrackingOptions` only prevents Amplitude from tracking default properties on newly created projects, where you haven't sent data yet. If you have a project with existing data and you want to stop collecting the default properties, get help in the [Amplitude Community](https://community.amplitude.com/?utm_source=devdocs&utm_medium=helpcontent&utm_campaign=devdocswebsite). Disabling tracking doesn't delete any existing data in your project. ### Carrier Amplitude determines the user's mobile carrier using [`CTTelephonyNetworkInfo`](https://developer.apple.com/documentation/coretelephony/cttelephonynetworkinfo), which returns the registered operator of the `sim`. ### COPPA control You can enable or disable COPPA (Children's Online Privacy Protection Act) restrictions on IDFA, IDFV, city, IP address, and location tracking at one time. Apps that ask for information from children under 13 years of age must comply with COPPA. #### Swift ```swift let amplitude = Amplitude( configuration: Configuration( apiKey: AMPLITUDE_API_KEY, enableCoppaControl: true ) ) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY]; configuration.enableCoppaControl = true; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` ### Advertiser ID Advertiser ID (also referred to as IDFA) is a unique identifier provided by the iOS and Google Play stores. Because it's unique to every person and not only their devices, it's useful for mobile attribution. [Mobile attribution](https://www.adjust.com/blog/mobile-ad-attribution-introduction-for-beginners/) is the attribution of an installation of a mobile app to its original source (such as ad campaign, app store search). Mobile apps need permission to ask for IDFA, and apps targeted to children can't track at all. Consider using IDFV, device ID, or an email login system when IDFA isn't available. To retrieve the IDFA and add it to tracking events, follow this [example plugin](https://github.com/amplitude/Amplitude-Swift/blob/main/Examples/AmplitudeSwiftUIExample/AmplitudeSwiftUIExample/ExamplePlugins/IDFACollectionPlugin.swift) to implement your own plugin. ### Device ID lifecycle The SDK initializes the device ID in the following order, and sets the device ID to the first valid value encountered: 1. Device ID of Amplitude instance if you set it by `setDeviceId()`. 2. IDFV if it exists. 3. A randomly generated UUID string. #### One user with multiple devices A single user may have multiple devices, each with a different device ID. To ensure coherence, set the user ID consistently across all these devices. Even though the device IDs differ, Amplitude can still merge them into a single Amplitude ID and identify them as a unique user. #### Transfer to a new device Multiple devices can have the same device ID when a user switches to a new device. When users transition to a new device, they often transfer their applications along with other relevant data. The specific transferred content may vary by application. In general, it includes databases and file directories associated with the app. However, the exact items included depend on the app's design and the choices the developers made. If a user backed up databases or file directories from one device to another, the device ID stored within them may still be present. As a result, if the SDK retrieves it during initialization, different devices might end up using the same device ID. #### Get device ID Use the helper method `getDeviceId()` to get the value of the current `deviceId`. #### Swift ```swift let deviceId = amplitude.getDeviceId() ``` #### Obj-C ```objc NSString *deviceId = [amplitude getDeviceId]; ``` To set the device, refer to [custom device ID](#custom-device-id). ### Location tracking Amplitude converts the IP of a user event into a location (GeoIP lookup) by default. An app's own tracking solution or user data can override this information. ### Opt users out of tracking Users may want to opt out of tracking entirely, which means Amplitude doesn't track any of their events or browsing history. `OptOut` provides a way to fulfill a user's requests for privacy. #### Swift ```swift let amplitude = Amplitude( configuration: Configuration( apiKey: AMPLITUDE_API_KEY, optOut: true ) ) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY]; configuration.optOut = true; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` ### Set log callback Implement a customized `loggerProvider` class from the LoggerProvider, and pass it in the configuration during initialization to help collect error messages from the SDK in a production environment. #### Swift ```swift class SampleLogger: Logger { typealias LogLevel = LogLevelEnum var logLevel: Int init(logLevel: Int = LogLevelEnum.off.rawValue) { self.logLevel = logLevel } func error(message: String) { // TODO: handle error message } func warn(message: String) { // TODO: handle warn message } func log(message: String) { // TODO: handle log message } func debug(message: String) { // TODO: handle debug message } } let amplitude = Amplitude( configuration: Configuration( apiKey: AMPLITUDE_API_KEY, loggerProvider: SampleLogger() ) ) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY]; configuration.loggerProvider = ^(NSInteger logLevel, NSString * _Nonnull message) { switch(logLevel) { case AMPLogLevelERROR: // TODO: handle error message break; case AMPLogLevelWARN: // TODO: handle warn message break; case AMPLogLevelLOG: // TODO: handle log message break; case AMPLogLevelDEBUG: // TODO: handle debug message break; } }; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` ### Security iOS automatically protects application data by storing each app's data in its own secure directory. Other applications usually can't access this directory. However, if a device is jailbroken, apps get root access to all directories on the device. To prevent other apps from accessing your app's Amplitude data on a jailbroken device, Amplitude recommends setting a unique instance name for your SDK. This creates a unique database that's isolated from other apps. #### Swift ```swift let amplitude = Amplitude( configuration: Configuration( apiKey: "API-KEY", instanceName: "my-unique-instance-name" ) ) ``` #### Obj-C ```objc AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:@"API-KEY" instanceName:@"my-unique-instance-name"]; Amplitude *amplitude = [Amplitude instanceWithConfiguration:configuration]; ``` ### Offline mode Beginning with version 1.3.0, the Amplitude iOS Swift SDK supports offline mode. The SDK checks network connectivity every time it tracks an event. If the device has a network connection, the SDK schedules a flush. If not, the SDK saves the event to storage. The SDK also listens for changes in network connectivity and flushes all stored events when the device reconnects. To disable offline mode, add `offline: NetworkConnectivityCheckerPlugin.Disabled` on initialization: #### Swift ```swift let amplitude = Amplitude( configuration: Configuration( apiKey: "API-KEY", offline: NetworkConnectivityCheckerPlugin.Disabled ) ) ``` #### Obj-C ```obj-c AMPConfiguration *configuration = [AMPConfiguration initWithApiKey:AMPLITUDE_API_KEY]; configuration.offline = AMPNetworkConnectivityCheckerPlugin.Disabled; Amplitude *amplitude = [Amplitude initWithConfiguration:configuration]; ``` You can also implement your own offline logic: 1. Disable the default offline logic as above. 2. Toggle `amplitude.configuration.offline` yourself. ### Apple privacy manifest Starting December 8, 2020, Apple requires a privacy manifest file for all new apps and app updates. Apple expects to make this mandatory in the Spring of 2024. Because Amplitude is a third party to your app, you need to make sure you properly disclose to your users the ways you use Amplitude with their data. > **Note:** Update the privacy manifest based on your app > > Amplitude sets the privacy manifest based on a default configuration. Update the privacy manifest according to your configuration and your app. #### NSPrivacyTracking > **Note:** Tracking definition > > Tracking refers to the act of linking user or device data collected from your app with user or device data collected from other companies' apps, websites, or offline properties for targeted advertising or advertising measurement purposes. For more information, refer to Apple's article [User privacy and data use](https://developer.apple.com/app-store/user-privacy-and-data-use/). By default, Amplitude doesn't use data for tracking. Add this field and set it to true if your app does. #### NSPrivacyCollectedDataTypes | Date type | Linked to user | Used for tracking | Reason for collection | Where it's tracked | | --- | --- | --- | --- | --- | | Product interaction | Yes | No | Analytics | Such as app launches, taps, clicks, scrolling information, music listening data, video views, saved place in a game, video, or song, or other information about how the user interacts with the app. | | Device ID | Yes | No | Analytics | Tracked by default. Refer to [Device ID lifecycle](#device-id-lifecycle). | | Coarse Location | Yes | No | Analytics | Country, region, and city based on IP address. Amplitude doesn't collect them from device GPS or location features. | By default, the SDK tracks `deviceId` only. You can use `setUserId()` to track `userId` as well. To do so, add the "User ID" Data type. For more information about data types, refer to Apple's article [Describing data use in privacy manifests](https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_data_use_in_privacy_manifests). #### NSPrivacyTrackingDomains If you set `NSPrivacyTracking` to true, provide at least one internet domain in `NSPrivacyTrackingDomains` based on your configuration. | Domain | Description | | --- | --- | | https://api2.amplitude.com/2/httpapi | The default HTTP V2 endpoint. | | https://api.eu.amplitude.com/2/httpapi | EU endpoint if `configuration.serverZone = EU`. | | https://api2.amplitude.com/batch | Batch endpoint if `configuration.useBatch = true`. | | https://api.eu.amplitude.com/batch | Batch EU endpoint if `configuration.useBatch = true` and `configuration.serverZone = EU`. | #### NSPrivacyAccessedAPITypes The SDK only uses `userDefaults` API for identity storage. #### Create your app's privacy report Follow the steps on how to [create your app's privacy](https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_data_use_in_privacy_manifests#4239187). ================================================================================ # Android-Kotlin SDK URL: https://amplitude.com/docs/sdks/analytics/android/android-kotlin-sdk ================================================================================ # Android-Kotlin SDK - **Package:** `com.amplitude:analytics-android` ([maven](https://search.maven.org/artifact/com.amplitude/analytics-android)) - **Latest version:** 1.30.1 The Android Kotlin SDK (`com.amplitude:analytics-android`) instruments Android apps and sends events to Amplitude. Use it for new Android apps and for Kotlin or Java clients that need sessions, autocapture, and the plugin pipeline. If you still depend on the maintenance Android SDK (`com.amplitude:android-sdk`), [migrate to this SDK](https://amplitude.com/docs/sdks/analytics/android/migrate-to-the-android-kotlin-sdk). #### Recent features - Frustration Analytics (v1.22.0+): Automatically detect and track rage clicks and dead clicks to identify areas of user frustration in your app. Configure tracking for both Android Views and Jetpack Compose, with options to [ignore specific elements](#ignore-specific-elements-from-frustration-analytics). Refer to [Track frustration interactions](#track-frustration-interactions). - Network Tracking Plugin (v1.21.0+): Track network requests and responses through OkHttp, including request/response sizes, status codes, and timing information. Requires manual integration as an OkHttp interceptor. Refer to [Network Tracking Plugin](#network-tracking-plugin). - Enhanced Jetpack Compose support (v1.21.3+): Full autocapture support for all clickable Compose elements with improved element identification. Refer to [Track element interactions](#track-element-interactions). - Element Interactions Autocapture (v1.17.0+): Track user interactions with clickable UI elements in both Android Views and Jetpack Compose automatically. Refer to [Track element interactions](#track-element-interactions). - Fragment Autocapture (v1.18.0+): Automatically capture fragment views with detailed fragment properties including class, identifier, and tag. Refer to [Track screen views](#track-screen-views). - Advanced Identify operations: Full support for user property operations including `clearAll()` to remove all user properties. Refer to [Identify](#identify). > **Note:** Location tracking default change > > As of v1.20.7, the SDK disables location tracking by default. Set the `locationListening` option to `true` to track location data. Refer to [Location tracking](#location-tracking). ## System requirements The Android Kotlin SDK supports Android API level 21 (Android 5.0 Lollipop) and higher. ## Install the SDK Amplitude recommends using Android Studio as an IDE and Gradle to manage dependencies. #### Gradle If you use Gradle in your project, add the following dependency to `build.gradle`, and sync your project with the updated file. ```groovy dependencies { implementation 'com.amplitude:analytics-android:1.+' } ``` #### Maven If you use Maven in your project, Maven Central hosts the .jar with the following configuration in `pom.xml`. ```xml com.amplitude analytics-android [1.0,2.0] ``` ## Initialize the SDK Initialize the SDK before you track events. You need your Amplitude project API key and your Android application context. Initialize once per process and reuse that instance. #### Kotlin ```kotlin import com.amplitude.android.Amplitude val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { // Set configuration options here. } ``` #### Java ```java import com.amplitude.android.Amplitude; import com.amplitude.android.ConfigurationBuilder; ConfigurationBuilder builder = new ConfigurationBuilder(AMPLITUDE_API_KEY, getApplicationContext()); Amplitude amplitude = new Amplitude(builder.build()); ``` ### Where to initialize Amplitude recommends initializing in `Application.onCreate` so the SDK is ready before any Activity starts and autocapture registers for the full app lifecycle. ```kotlin import android.app.Application import com.amplitude.android.Amplitude class MyApplication : Application() { override fun onCreate() { super.onCreate() amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { // Set configuration options here. } } companion object { lateinit var amplitude: Amplitude } } ``` > **Note:** > > Pass the application context, not an Activity context. The SDK requires an Application to observe the app lifecycle. ### Dependency injection If you use a DI framework such as Hilt, Koin, or Dagger, provide Amplitude as an application-scoped singleton built with the application context, and inject that instance wherever you track events. Keep the following in mind: - Create one instance per process. Instances that share an `instanceName` share storage and identity. - Construct the instance first, then call `setUserId`, then track. For available configuration options, refer to [Configure the SDK](#configure-the-sdk). ## Configure the SDK #### Configuration options | Name | Description | Default Value | | --- | --- | --- | | `deviceId` | `String?`. The device ID to use for this device. If you don't provide a device ID, the SDK generates one automatically. Learn more in [Device ID lifecycle](#device-id-lifecycle). | `null` | | `flushIntervalMillis` | `Int`. The amount of time the SDK waits before attempting to upload unsent events to the server or reach the `flushQueueSize` threshold. The value is in milliseconds. | `30000` | | `flushQueueSize` | `Int`. The SDK attempts to upload after the unsent event count exceeds the event upload threshold or reaches the `flushIntervalMillis` interval. | `30` | | ~`flushMaxRetries`~ (Deprecated.) | `Int`. Deprecated. Upload retries aren't capped. Don't set this property. | `5` | | `minIdLength` | `Int?`. The minimum length for user id or device id. When unset, the server enforces a minimum of 5 characters. | `null` | | `partnerId` | `String?`. The partner id for partner integration. | `null` | | `identifyBatchIntervalMillis` | `Long`. The amount of time the SDK waits before batching intercepted identify events. The value is in milliseconds. | `30000` | | `flushEventsOnClose` | `Boolean`. Flushing of unsent events on app close. | `true` | | `callback` | `EventCallBack`. Callback function after event sent. | `null` | | `optOut` | `Boolean`. Opt the user out of tracking. | `false` | | ~`trackingSessionEvents`~ (Deprecated. Use [`autocapture`](#autocapture) instead.) | `Boolean`. Automatic tracking of `session_start` and `session_end` events that count toward event volume. | `true` | | ~`defaultTracking`~ (Deprecated. Use [`autocapture`](#autocapture) instead.) | `DefaultTrackingOptions`. Enable tracking of default events for sessions, app lifecycles, screen views, and deep links. | `DefaultTrackingOptions(sessions = true)` | | `autocapture` | `Set`. A `Set` of Options to enable tracking of default events for sessions, application lifecycles, screen and fragment views, deep links, and element interactions. | If you don't set this parameter, the SDK adds `AutocaptureOption.SESSIONS` to the `Set` by default. For more information, refer to [Autocapture](#autocapture). | | `interactionsOptions` | `InteractionsOptions`. Configuration for granular control over frustration interaction tracking types (rage clicks and dead clicks). | `InteractionsOptions(rageClick = RageClickOptions(enabled = true), deadClick = DeadClickOptions(enabled = true))` | | `minTimeBetweenSessionsMillis` | `Long`. The amount of time for session timeout. The value is in milliseconds. | `300000` | | `sessionId` | `Long?`. Initial session ID to use. If not set, session management handles ID generation automatically. | `null` | | `serverUrl` | `String?`. The server URL events upload to. When unset, the SDK uses the HTTP V2 endpoint for the selected `serverZone`. A nonblank value overrides zone and batch endpoint selection. | `null` | | `serverZone` | `ServerZone.US` or `ServerZone.EU`. The server zone to send to. When `serverUrl` is null or blank, the SDK selects the HTTP V2 or batch endpoint for this zone. | `ServerZone.US` | | `plan` | `Plan?`. Tracking plan metadata attached to events. | `null` | | `ingestionMetadata` | `IngestionMetadata?`. Ingestion metadata attached to events. | `null` | | `httpClient` | `HttpClientInterface?`. Custom HTTP client implementation for event uploads. Implement the `HttpClientInterface` to use your own HTTP client. | `null` | | `useBatch` | `Boolean`. Whether to use the batch API. Selects the batch endpoint only when `serverUrl` is null or blank. | `false` | | `useAdvertisingIdForDeviceId` | `Boolean`. Whether to use advertising id as device id. For more information, refer to [Advertiser ID](#advertiser-id) for required module and permission. | `false` | | `useAppSetIdForDeviceId` | `Boolean`. Whether to use app set id as device id. For more information, refer to [Application ID](#app-set-id) for required module and permission. | `false` | | `trackingOptions` | `TrackingOptions`. Options to control the values tracked in SDK. | `TrackingOptions()` (disables no fields by default) | | `enableCoppaControl` | `Boolean`. Whether to enable COPPA control for tracking options. | `false` | | `instanceName` | `String`. The name of the instance. Instances with the same name share storage and identity. For isolated storage and identity, use a unique `instanceName` for each instance. | `$default_instance` | | `migrateLegacyData` | `Boolean`. Available in `1.9.0`+. Whether to migrate [maintenance Android SDK](https://amplitude.com/docs/sdks/analytics/android/android-sdk) data (events, user/device ID). For more information, refer to the [Amplitude-Kotlin RemnantDataMigration source](https://github.com/amplitude/Amplitude-Kotlin/blob/main/android/src/main/java/com/amplitude/android/migration/RemnantDataMigration.kt#L9-L16). | `true` | | `offline` | `Boolean?`. Whether the SDK has network connectivity. Set `null` or `AndroidNetworkConnectivityCheckerPlugin.Disabled` to disable the Android connectivity plugin. For more information, refer to [Offline mode](#offline-mode). | `false` | | `storageProvider` | `StorageProvider`. Implements `StorageProvider` interface to store events. | SDK-provided Android event storage | | `identifyInterceptStorageProvider` | `StorageProvider`. Implements `StorageProvider` interface for identify event interception and volume optimization. | SDK-provided identify intercept storage | | `identityStorageProvider` | `IdentityStorageProvider`. Implements `IdentityStorageProvider` to store user id and device id. | `FileIdentityStorageProvider` | | `loggerProvider` | `LoggerProvider`. Implements the `LoggerProvider` interface to emit log messages to the destination you choose. | `AndroidLoggerProvider` | | `newDeviceIdPerInstall` | `Boolean`. Whether to generate a different device ID on every install. This legacy configuration exists to keep compatibility with the maintenance Android SDK. When `true`, the SDK bypasses advertising ID, then falls through to App Set ID (if `useAppSetIdForDeviceId` is `true`) or a random ID. | `false` | | `locationListening` | `Boolean`. Whether to enable Android location service. For more information, refer to [Location tracking](#location-tracking). | `false` | | `enableAutocaptureRemoteConfig` | `Boolean`. Whether to enable remote configuration for autocapture options. | `true` | | `enableDiagnostics` | `Boolean`. Whether to send SDK diagnostic information to Amplitude to help improve the SDK. | `true` | | `enableRequestBodyCompression` | `Boolean`. Whether to gzip the request body. Only applies when you set a custom `serverUrl`; the SDK's default endpoints always compress request bodies. | `false` | ### Configure batching behavior To support high-performance environments, the SDK sends events in batches. The SDK queues every event logged by the `track` method in memory and flushes them in batches in the background. Customize batch behavior with `flushQueueSize` and `flushIntervalMillis`. When `serverUrl` is null or blank, `useBatch = true` selects the batch endpoint. A nonblank `serverUrl` overrides zone and batch endpoint selection. Both regular mode and batch mode use the same event upload threshold and flush time intervals. #### Kotlin ```kotlin import com.amplitude.android.Amplitude val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { flushIntervalMillis = 50000 flushQueueSize = 20 } ``` #### Java ```java import com.amplitude.android.Amplitude; import com.amplitude.android.ConfigurationBuilder; ConfigurationBuilder builder = new ConfigurationBuilder(AMPLITUDE_API_KEY, getApplicationContext()); builder.setFlushIntervalMillis(1000); builder.setFlushQueueSize(10); Amplitude amplitude = new Amplitude(builder.build()); ``` ### EU data residency Configure the server zone when initializing the client to send data to Amplitude's EU servers. The SDK sends data based on the server zone if you set it. > **Note:** > > For EU data residency, set up the project inside Amplitude EU. Initialize the SDK with the API key from Amplitude EU. #### Kotlin ```kotlin import com.amplitude.android.Amplitude val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { serverZone = ServerZone.EU } ``` #### Java ```java import com.amplitude.android.Amplitude; import com.amplitude.android.ConfigurationBuilder; ConfigurationBuilder builder = new ConfigurationBuilder(AMPLITUDE_API_KEY, getApplicationContext()); builder.setServerZone(ServerZone.EU); Amplitude amplitude = new Amplitude(builder.build()); ``` ### Custom HTTP client The SDK uses `HttpURLConnection` by default for network requests. To use a custom HTTP client, implement `HttpClientInterface` and pass it to the `httpClient` configuration option. #### OkHttp with gzip compression The sample app demonstrates how to create a custom OkHttp client with gzip compression for event uploads: - [GzipRequestInterceptor](https://github.com/amplitude/Amplitude-Kotlin/blob/main/samples/kotlin-android-app/src/main/java/com/amplitude/android/sample/GzipRequestInterceptor.kt) - OkHttp interceptor that compresses request bodies. - [CustomOkHttpClient](https://github.com/amplitude/Amplitude-Kotlin/blob/main/samples/kotlin-android-app/src/main/java/com/amplitude/android/sample/CustomOkHttpClient.kt) - `HttpClientInterface` implementation using OkHttp. To use the custom client: #### Kotlin ```kotlin val httpClient = CustomOkHttpClient() val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { this.httpClient = httpClient } httpClient.initialize(amplitude.configuration) ``` #### Java ```java import com.amplitude.android.Amplitude; import com.amplitude.android.Configuration; import com.amplitude.android.ConfigurationBuilder; CustomOkHttpClient httpClient = new CustomOkHttpClient(); ConfigurationBuilder builder = new ConfigurationBuilder(AMPLITUDE_API_KEY, getApplicationContext()); builder.setHttpClient(httpClient); Configuration configuration = builder.build(); httpClient.initialize(configuration); Amplitude amplitude = new Amplitude(configuration); ``` > **Note:** > > The SDK's default HTTP client already compresses request bodies using gzip. Use a custom OkHttp client when you need additional features like custom timeouts, certificate pinning, or logging interceptors. ## Track Events represent how users interact with your application. For example, "Song Played" may be an action you want to note. ```kotlin amplitude.track("Song Played") ``` ## Verify your setup and ingestion > **Tip:** Verify first event ingestion > > By defaults, the Android Kotlin SDK queues events and uploads them every 30 seconds or after 30 events, whichever comes first. To check an event immediately, call `amplitude.flush()` after `track()`. > > Configure `loggerProvider` with a logger that uses `Logger.LogMode.DEBUG`. Send its `debug`, `info`, `warn`, and `error` methods to Android's `Log` methods with the tag `Amplitude`. For example, the provider and debug method use this pattern: > > ```kotlin > import android.util.Log > import com.amplitude.common.Logger > import com.amplitude.core.LoggerProvider > > class DebugLogger : Logger { > override var logMode: Logger.LogMode > get() = Logger.LogMode.DEBUG > set(value) {} > > override fun debug(message: String) { > Log.d("Amplitude", message) > } > > override fun info(message: String) { > Log.i("Amplitude", message) > } > > override fun warn(message: String) { > Log.w("Amplitude", message) > } > > override fun error(message: String) { > Log.e("Amplitude", message) > } > } > > class DebugLoggerProvider : LoggerProvider { > override fun getLogger(amplitude: com.amplitude.core.Amplitude): Logger = DebugLogger() > } > > val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { > loggerProvider = DebugLoggerProvider() > } > ``` > > In Android Studio, open Logcat and filter with `tag:Amplitude`. Confirm that the SDK queues and uploads the event without an error. > > Open [User Lookup activity](https://amplitude.com/docs/analytics/user-data-lookup#activity), find the event's user or device ID, and enable **Live event updates**. Confirm that the event appears in the activity stream. You can also optionally include event properties. ```kotlin amplitude.track( "Song Played", mutableMapOf("title" to "Happy Birthday") ) ``` For more complex events you can [create and track a `BaseEvent` object](https://github.com/amplitude/Amplitude-Kotlin/blob/8c3c39ce1f79485a0ce716bbf01de464a9afe9a8/core/src/main/java/com/amplitude/core/Amplitude.kt#L112). ```kotlin var event = BaseEvent() event.eventType = "Song Played" event.eventProperties = mutableMapOf("title" to "Happy Birthday") event.groups = mutableMapOf("test-group-type" to "test-group-value") event.insertId = "1234" amplitude.track(event) ``` ## Identify > **Note:** > > Starting in release v1.7.0, the SDK batches `identify` events that contain only `set` operations. This batching reduces the number of sent events and doesn't affect how `set` operations run. Use the `identifyBatchIntervalMillis` configuration setting to manage the interval at which the SDK flushes batched identify intercepts. Identify sets the user properties of a particular user without sending any event. The SDK supports the operations `set`, `setOnce`, `unset`, `add`, `append`, `prepend`, `preInsert`, `postInsert`, `remove`, and `clearAll` on individual user properties. Use the Identify interface to declare the operations. You can chain multiple operations in a single Identify object, then pass the Identify object to the Amplitude client to send to the server. > **Note:** > > If you send the Identify call after the event, the results of operations appear immediately in the dashboard user's profile area, but they don't appear in chart results until the SDK sends another event after the Identify call. The identify call only affects events going forward. Use the identify methods to handle a user's identity. Proper use of these methods connects events to the correct user as they move across devices, browsers, and other platforms. Send an identify call containing those user property operations to the Amplitude server to tie a user's events to specific user properties. ```kotlin val identify = Identify() identify.set("color", "green") amplitude.identify(identify) ``` ### Identify operations The `Identify` object supports the following operations: | Operation | Description | | --- | --- | | `set` | Sets the value of a user property. Overwrites existing values. | | `setOnce` | Sets the value of a user property only once. Subsequent calls don't overwrite the initial value. | | `add` | Adds a numeric value to a numeric user property. | | `append` | Appends a value to a user property array. | | `prepend` | Prepends a value to a user property array. | | `preInsert` | Adds a value to the beginning of a user property array if it doesn't already exist in the array. | | `postInsert` | Adds a value to the end of a user property array if it doesn't already exist in the array. | | `remove` | Removes a value from a user property array. | | `unset` | Removes a user property. | | `clearAll` | Clears all user properties. | #### Kotlin ```kotlin val identify = Identify() identify .set("color", "green") .setOnce("initial_source", "organic") .add("login_count", 1) .append("visited_pages", "home") .prepend("notifications", "new_feature") .preInsert("tags", "beta") .postInsert("tags", "vip") .remove("visited_pages", "home") .unset("temporary_property") amplitude.identify(identify) ``` #### Java ```java Identify identify = new Identify(); identify .set("color", "green") .setOnce("initial_source", "organic") .add("login_count", 1) .append("visited_pages", "home") .prepend("notifications", "new_feature") .preInsert("tags", "beta") .postInsert("tags", "vip") .remove("visited_pages", "home") .unset("temporary_property"); amplitude.identify(identify); ``` ### Clear all user properties Use `clearAll()` to clear all user properties for the current user. This operation is irreversible. > **Warning:** Use with caution > > The `clearAll()` operation removes all user properties. This action is permanent. You can't undo it. #### Kotlin ```kotlin val identify = Identify() identify.clearAll() amplitude.identify(identify) ``` #### Java ```java Identify identify = new Identify(); identify.clearAll(); amplitude.identify(identify); ``` ## Autocapture Starting from release v1.18.0, the SDK can track more events without manual instrumentation. Configure the SDK to track the following events automatically: - Sessions. - App lifecycles. - Screen views. - Deep links. - Element interactions. - Frustration interactions: - Rage clicks. - Dead clicks. #### Autocapture options | Name | Type | Enabled by default | Description | | --- | --- | --- | --- | | `SESSIONS` | `AutocaptureOption` | Yes | Enables session tracking. When you set the option, Amplitude tracks `session_start` and `session_end` events. Otherwise, Amplitude doesn't track session events. When you don't set this option, Amplitude tracks `sessionId` only. Refer to [Track sessions](#track-sessions) for more information. | | `APP_LIFECYCLES` | `AutocaptureOption` | No | Enables application lifecycle events tracking. If you set the option, Amplitude tracks application installed, application updated, application opened, and application backgrounded events. Properties differ by event. Refer to [Track application lifecycles](#track-application-lifecycles) for more information. | | `SCREEN_VIEWS` | `AutocaptureOption` | No | Enables screen and fragment views tracking. If you set the option, Amplitude tracks screen viewed and fragment viewed events. Tracked event properties include: `[Amplitude] Screen Name`, `[Amplitude] Fragment Class`, `[Amplitude] Fragment Identifier`, `[Amplitude] Fragment Tag`. Refer to [Track screen views](#track-screen-views) for more information. | | `DEEP_LINKS` | `AutocaptureOption` | No | Enables deep link tracking. If you set the option, Amplitude tracks deep link opened events. Tracked event properties include: `[Amplitude] Link URL`, `[Amplitude] Link Referrer`. Refer to [Track deep links](#track-deep-links) for more information. | | `ELEMENT_INTERACTIONS` | `AutocaptureOption` | No | Enables element interaction tracking. If you set the option, Amplitude tracks user interactions with clickable elements. Tracked event properties include: `[Amplitude] Action`, `[Amplitude] Target Class`, `[Amplitude] Target Resource`, `[Amplitude] Target Tag`, `[Amplitude] Target Accessibility Label`, `[Amplitude] Target Source`, `[Amplitude] Hierarchy`, `[Amplitude] Screen Name`. Refer to [Track element interactions](#track-element-interactions) for more information. | | `FRUSTRATION_INTERACTIONS` | `AutocaptureOption` | No | Enables frustration interaction tracking. When you enable the option, Amplitude tracks frustration interactions (rage clicks and dead clicks) with clickable UI elements. Rage clicks generate the `[Amplitude] Rage Click` event, and dead clicks generate the `[Amplitude] Dead Click` event. Refer to [Track frustration interactions](#track-frustration-interactions) for more information. | Configure Amplitude to start tracking Autocapture events. Otherwise, omit the configuration to keep only session tracking enabled. #### Kotlin The `autocapture` configuration accepts a `Set` of `AutocaptureOption` values. To create the Autocapture options, use the `autocaptureOptions` helper function and add the options to the set with a unary plus sign (`+`) before each option. ```kotlin import com.amplitude.android.Amplitude val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { autocapture = autocaptureOptions { +sessions // or `+AutocaptureOption.SESSIONS` +appLifecycles // or `+AutocaptureOption.APP_LIFECYCLES` +deepLinks // or `+AutocaptureOption.DEEP_LINKS` +screenViews // or `+AutocaptureOption.SCREEN_VIEWS` +elementInteractions // or `+AutocaptureOption.ELEMENT_INTERACTIONS` +frustrationInteractions // or `+AutocaptureOption.FRUSTRATION_INTERACTIONS` } } ``` By default, if you don't explicitly set the `autocapture` configuration during initialization, `configuration.autocapture` automatically includes `AutocaptureOption.SESSIONS`. To prevent automatic session event capture, set `autocapture` without the `AutocaptureOption.SESSIONS` option. ```kotlin import com.amplitude.android.Amplitude val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { autocapture = setOf(AutocaptureOption.APP_LIFECYCLES) // or use `setOf()` to disable autocapture. } ``` #### Java The `autocapture` configuration accepts a `Set` of `AutocaptureOption` values. ```java import com.amplitude.android.Amplitude; import com.amplitude.android.AutocaptureOption; import com.amplitude.android.ConfigurationBuilder; ConfigurationBuilder builder = new ConfigurationBuilder(AMPLITUDE_API_KEY, getApplicationContext()); builder.getAutocapture().add(AutocaptureOption.SESSIONS); builder.getAutocapture().add(AutocaptureOption.APP_LIFECYCLES); builder.getAutocapture().add(AutocaptureOption.DEEP_LINKS); builder.getAutocapture().add(AutocaptureOption.SCREEN_VIEWS); builder.getAutocapture().add(AutocaptureOption.ELEMENT_INTERACTIONS); builder.getAutocapture().add(AutocaptureOption.FRUSTRATION_INTERACTIONS); Amplitude amplitude = new Amplitude(builder.build()); ``` By default, if you don't explicitly set the `autocapture` configuration during initialization, `builder.getAutocapture()` automatically includes `AutocaptureOption.SESSIONS`. To prevent automatic session event capture, remove the `AutocaptureOption.SESSIONS` option from `autocapture`. ```java import com.amplitude.android.Amplitude; import com.amplitude.android.ConfigurationBuilder; ConfigurationBuilder builder = new ConfigurationBuilder(AMPLITUDE_API_KEY, getApplicationContext()); builder.getAutocapture().remove(AutocaptureOption.SESSIONS); Amplitude amplitude = new Amplitude(builder.build()); ``` ### Track sessions Amplitude enables session tracking by default. Include `AutocaptureOption.SESSIONS` in the `autocapture` configuration to explicitly configure the SDK to track session events, or to enable session event tracking along with other Autocapture configurations. #### Kotlin ```kotlin import com.amplitude.android.Amplitude val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { autocapture = autocaptureOptions { +sessions // or `+AutocaptureOption.SESSIONS` } } ``` #### Java ```java import com.amplitude.android.Amplitude; import com.amplitude.android.ConfigurationBuilder; ConfigurationBuilder builder = new ConfigurationBuilder(AMPLITUDE_API_KEY, getApplicationContext()); // `AutocaptureOption.SESSIONS` is included by default. Amplitude amplitude = new Amplitude(builder.build()); ``` For more information about session tracking, refer to [User sessions](#user-sessions). ### Track application lifecycles Enable application lifecycle event tracking by including `AutocaptureOption.APP_LIFECYCLES` in the `autocapture` configuration. Refer to the following code sample. #### Kotlin ```kotlin import com.amplitude.android.Amplitude val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { autocapture = autocaptureOptions { +appLifecycles // or `+AutocaptureOption.APP_LIFECYCLES` } } ``` #### Java ```java import com.amplitude.android.Amplitude; import com.amplitude.android.ConfigurationBuilder; ConfigurationBuilder builder = new ConfigurationBuilder(AMPLITUDE_API_KEY, getApplicationContext()); builder.getAutocapture().add(AutocaptureOption.APP_LIFECYCLES); Amplitude amplitude = new Amplitude(builder.build()); ``` After you enable this setting, Amplitude tracks the following events: - `[Amplitude] Application Installed`: fires when a user opens the application for the first time right after installation. Properties: `[Amplitude] Version`, `[Amplitude] Build`. - `[Amplitude] Application Updated`: fires when a user opens the application after updating the application. Properties: `[Amplitude] Previous Version`, `[Amplitude] Previous Build`, `[Amplitude] Version`, `[Amplitude] Build`. - `[Amplitude] Application Opened`: fires when a user launches or foregrounds the application after the first open. Properties: `[Amplitude] From Background`, `[Amplitude] Version`, `[Amplitude] Build`. - `[Amplitude] Application Backgrounded`: fires when a user backgrounds the application. This event has no properties. ### Track screen views Enable screen and fragment view event tracking by including `AutocaptureOption.SCREEN_VIEWS` in the `autocapture` configuration. Refer to the following code sample. #### Kotlin ```kotlin import com.amplitude.android.Amplitude val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { autocapture = autocaptureOptions { +screenViews // or `+AutocaptureOption.SCREEN_VIEWS` } } ``` #### Java ```java import com.amplitude.android.Amplitude; import com.amplitude.android.ConfigurationBuilder; ConfigurationBuilder builder = new ConfigurationBuilder(AMPLITUDE_API_KEY, getApplicationContext()); builder.getAutocapture().add(AutocaptureOption.SCREEN_VIEWS); Amplitude amplitude = new Amplitude(builder.build()); ``` After you enable this setting, Amplitude tracks both `[Amplitude] Screen Viewed` and `[Amplitude] Fragment Viewed` events. Both events include a screen name property. For `[Amplitude] Fragment Viewed` events, Amplitude captures additional fragment-specific properties. #### Event properties descriptions | Event property | Description | | --- | --- | | `[Amplitude] Screen Name` | The activity title, activity label, activity name, or activity class name, in that order. Application name is the fallback only if that lookup throws. | | `[Amplitude] Fragment Class` | The fully qualified class name of the viewed fragment. | | `[Amplitude] Fragment Identifier` | The fragment resource name. This is either the layout `android:id` or the container view ID you supply when adding the fragment. | | `[Amplitude] Fragment Tag` | The unique identifier assigned to the fragment during a transaction. | ### Track deep links Enable deep link event tracking by including `AutocaptureOption.DEEP_LINKS` in the `autocapture` configuration. Refer to the following code sample. #### Kotlin ```kotlin import com.amplitude.android.Amplitude val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { autocapture = autocaptureOptions { +deepLinks // or `+AutocaptureOption.DEEP_LINKS` } } ``` #### Java ```java import com.amplitude.android.Amplitude; import com.amplitude.android.ConfigurationBuilder; ConfigurationBuilder builder = new ConfigurationBuilder(AMPLITUDE_API_KEY, getApplicationContext()); builder.getAutocapture().add(AutocaptureOption.DEEP_LINKS); Amplitude amplitude = new Amplitude(builder.build()); ``` After you enable this setting, Amplitude tracks the `[Amplitude] Deep Link Opened` event with the URL and referrer information. #### Handle deep links in single-task activities If your activity uses `singleTop`, `singleTask`, or `singleInstance` launch mode, Android delivers deep links that arrive while the activity is already running to `onNewIntent()` instead of creating a new activity. In this case, call `setIntent()` to update the activity's intent so Amplitude can track the deep link. #### Kotlin ```kotlin override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) // Required for Amplitude to track the deep link } ``` #### Java ```java @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); // Required for Amplitude to track the deep link } ``` > **Note:** > > Without calling `setIntent()`, `getIntent()` continues to return the original intent that started the activity, and Amplitude doesn't detect the new deep link. ### Track element interactions Amplitude can track user interactions with clickable elements, with support for both classic Android Views and Jetpack Compose. To enable this option, include `AutocaptureOption.ELEMENT_INTERACTIONS` in the `autocapture` configuration. #### Kotlin ```kotlin import com.amplitude.android.Amplitude val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { autocapture = autocaptureOptions { +elementInteractions // or `+AutocaptureOption.ELEMENT_INTERACTIONS` } } ``` #### Java ```java import com.amplitude.android.Amplitude; import com.amplitude.android.ConfigurationBuilder; ConfigurationBuilder builder = new ConfigurationBuilder(AMPLITUDE_API_KEY, getApplicationContext()); builder.getAutocapture().add(AutocaptureOption.ELEMENT_INTERACTIONS); Amplitude amplitude = new Amplitude(builder.build()); ``` When you enable this setting, Amplitude tracks the `[Amplitude] Element Interacted` event whenever a user interacts with an element in the application. #### Event properties descriptions | Event property | Description | | --- | --- | | `[Amplitude] Action` | The action that triggered the event. Defaults to `touch`. | | `[Amplitude] Target Class` | The canonical name of the target view class. | | `[Amplitude] Target Resource` | The resource entry name for the target view identifier within the context the view is running in. | | `[Amplitude] Target Tag` | The tag of the target view if the value is of primitive type, or the `Modifier.testTag` of the target `@Composable` function if provided. This property is optional for Compose elements. | | `[Amplitude] Target Text` | The text of the target view if the view is a `Button` instance. Compose omits this property. | | `[Amplitude] Target Accessibility Label` | The accessibility label of the target element. | | `[Amplitude] Target Source` | The underlying framework of the target element, either `Android View` or `Jetpack Compose`. | | `[Amplitude] Hierarchy` | The target view's parent chain, from the clicked view up through its ancestors. Compose omits this property. | | `[Amplitude] Screen Name` | Refer to [Track screen views](#track-screen-views). | Jetpack Compose omits `[Amplitude] Target Class`, `[Amplitude] Target Resource`, `[Amplitude] Target Text`, and `[Amplitude] Hierarchy`. > **Info:** Support for Jetpack Compose > > Amplitude tracks user interactions with all clickable UI elements implemented in Jetpack Compose. `Modifier.testTag` is optional. Add it to `@Composable` functions to provide additional identification in the `[Amplitude] Target Tag` property. If you don't set `testTag`, Amplitude still tracks the interaction with `[Amplitude] Target Source` set to `Jetpack Compose`. > > #### Use testTag for better element identification > > While `testTag` is optional, Amplitude recommends that you identify specific Compose views that users clicked. The `testTag` property provides several benefits: > > - Precise element identification: helps distinguish between similar UI elements (like multiple buttons or cards) in your analytics data. > - Stable tracking: provides a consistent identifier that doesn't change when you update or modify the UI structure or styling. > - Easier analysis: enables easier filtering and analysis of interactions with specific elements in Amplitude charts. > - Cross-platform consistency: maintains consistent element naming across different platforms. > > ```kotlin > // Example: Adding testTag for better identification > Button( > onClick = { /* handle click */ }, > modifier = Modifier.testTag("login_button") > ) { > Text("Log In") > } > > Card( > onClick = { /* handle click */ }, > modifier = Modifier.testTag("product_card_${product.id}") > ) { > // Card content > } > ``` > > When a user clicks these elements, the `[Amplitude] Target Tag` property contains the `testTag` value, making it easy to identify which specific element the user interacted with in your analytics data. ### Track frustration interactions Amplitude can track frustration interactions (Rage Clicks and Dead Clicks) with clickable UI elements in both Android Views and Jetpack Compose. To enable this option, include `AutocaptureOption.FRUSTRATION_INTERACTIONS` in the `autocapture` configuration. #### Kotlin ```kotlin import com.amplitude.android.Amplitude val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { autocapture = autocaptureOptions { +frustrationInteractions // or `+AutocaptureOption.FRUSTRATION_INTERACTIONS` } } ``` #### Java ```java import com.amplitude.android.Amplitude; import com.amplitude.android.ConfigurationBuilder; ConfigurationBuilder builder = new ConfigurationBuilder(AMPLITUDE_API_KEY, getApplicationContext()); builder.getAutocapture().add(AutocaptureOption.FRUSTRATION_INTERACTIONS); Amplitude amplitude = new Amplitude(builder.build()); ``` A rage click occurs when a user clicks the same element 4 or more times within 1 second, with each click no more than 50 device-independent pixels apart. When a Rage Click occurs, Amplitude tracks the `[Amplitude] Rage Click` event. #### Event properties descriptions | Event property | Description | | --- | --- | | `[Amplitude] Begin Time` | The timestamp when the interaction began, in milliseconds since Unix epoch. | | `[Amplitude] End Time` | The timestamp when the interaction ended, in milliseconds since Unix epoch. | | `[Amplitude] Duration` | The duration of the interaction in milliseconds. | | `[Amplitude] X` | The x-coordinate of the first click from the top-left corner of the screen. | | `[Amplitude] Y` | The y-coordinate of the first click from the top-left corner of the screen. | | `[Amplitude] Click Count` | The number of clicks that occurred. | | `[Amplitude] Clicks` | The array of clicks that occurred. | | `[Amplitude] Clicks[].X` | The x-coordinate of the click from the top-left corner of the screen. | | `[Amplitude] Clicks[].Y` | The y-coordinate of the click from the top-left corner of the screen. | | `[Amplitude] Clicks[].timestamp` | The timestamp of the click, in milliseconds since Unix epoch. | | `[Amplitude] Action` | The action that triggered the event. Defaults to `touch`. | | `[Amplitude] Target Class` | The canonical name of the target view class. Compose omits this property. | | `[Amplitude] Target Resource` | The resource entry name for the target view identifier within the context the view is running in. Compose omits this property. | | `[Amplitude] Target Tag` | The tag of the target view if the value is of primitive type, or the `Modifier.testTag` of the target `@Composable` function if provided. | | `[Amplitude] Target Text` | The text of the target view if the view is a `Button` instance. Compose omits this property. | | `[Amplitude] Target Accessibility Label` | The accessibility label of the target element. | | `[Amplitude] Target Source` | The underlying framework of the target element, either `Android View` or `Jetpack Compose`. | | `[Amplitude] Hierarchy` | The target view's parent chain, from the clicked view up through its ancestors. Compose omits this property. | | `[Amplitude] Screen Name` | Refer to [Track screen views](#track-screen-views). | A dead click is a user interaction on an interactive element that produces no visible change in the following 3 seconds. When a Dead Click occurs, Amplitude tracks the `[Amplitude] Dead Click` event. #### Event properties descriptions | Event property | Description | | --- | --- | | `[Amplitude] Begin Time` | The timestamp when the click occurred, in milliseconds since Unix epoch. | | `[Amplitude] End Time` | The timestamp when the 3-second timeout ended, in milliseconds since Unix epoch. | | `[Amplitude] Duration` | Always `3000`. This is the dead-click timeout, not a measured UI delay. | | `[Amplitude] Click Count` | The number of clicks. Always `1` for a dead click. | | `[Amplitude] X` | The x-coordinate of the click from the top-left corner of the screen. | | `[Amplitude] Y` | The y-coordinate of the click from the top-left corner of the screen. | | `[Amplitude] Action` | The action that triggered the event. Defaults to `touch`. | | `[Amplitude] Target Class` | The canonical name of the target view class. Compose omits this property. | | `[Amplitude] Target Resource` | The resource entry name for the target view identifier within the context the view is running in. Compose omits this property. | | `[Amplitude] Target Tag` | The tag of the target view if the value is of primitive type, or the `Modifier.testTag` of the target `@Composable` function if provided. | | `[Amplitude] Target Text` | The text of the target view if the view is a `Button` instance. Compose omits this property. | | `[Amplitude] Target Accessibility Label` | The accessibility label of the target element. | | `[Amplitude] Target Source` | The underlying framework of the target element, either `Android View` or `Jetpack Compose`. | | `[Amplitude] Hierarchy` | The target view's parent chain, from the clicked view up through its ancestors. Compose omits this property. | | `[Amplitude] Screen Name` | Refer to [Track screen views](#track-screen-views). | ### Configure frustration interaction types Enabling `FRUSTRATION_INTERACTIONS` tracks both rage clicks and dead clicks. Use the `interactionsOptions` parameter to enable or disable each type individually. #### Kotlin ```kotlin import com.amplitude.android.Amplitude import com.amplitude.android.InteractionsOptions import com.amplitude.android.RageClickOptions import com.amplitude.android.DeadClickOptions val amplitude = Amplitude(AMPLITUDE_API_KEY, applicationContext) { autocapture = autocaptureOptions { +frustrationInteractions } interactionsOptions = InteractionsOptions( rageClick = RageClickOptions(enabled = true), deadClick = DeadClickOptions(enabled = false) ) } ``` #### Java ```java import com.amplitude.android.Amplitude; import com.amplitude.android.ConfigurationBuilder; import com.amplitude.android.InteractionsOptions; import com.amplitude.android.RageClickOptions; import com.amplitude.android.DeadClickOptions; ConfigurationBuilder builder = new ConfigurationBuilder(AMPLITUDE_API_KEY, getApplicationContext()); builder.getAutocapture().add(AutocaptureOption.FRUSTRATION_INTERACTIONS); builder.setInteractionsOptions( new InteractionsOptions( new RageClickOptions(true), new DeadClickOptions(false) ) ); Amplitude amplitude = new Amplitude(builder.build()); ``` > **Note:** Dead clicks require Session Replay > > To track dead clicks, enable both Session Replay and frustration interactions. ### Ignore specific elements from frustration analytics Some UI elements generate expected rapid clicks or don't provide meaningful frustration signals. Use the ignore APIs to exclude these elements from frustration analytics while still tracking regular interaction events. Common use cases: - Navigation elements: back buttons, close buttons, and drawer toggles. - Multi-click elements: increment/decrement buttons and like/favorite buttons. - Loading indicators: progress bars, spinners, and loading buttons. - Decorative elements: non-functional UI components. #### Android Views Use `FrustrationAnalyticsUtils` to ignore frustration analytics for Android Views: #### Kotlin ```kotlin import com.amplitude.android.FrustrationAnalyticsUtils // Ignore all frustration analytics for this view val backButton = findViewById