Amplitude Analytics Integration
Amplitude is a product analytics platform. It differs from Google Analytics by building behavioral models: who reached purchase, where they dropped off, which features retained users. Key tools include Funnels, Retention, Pathfinder, Behavioral Cohorts.
Installation
npm install @amplitude/analytics-browser
// src/analytics/amplitude.ts
import * as amplitude from '@amplitude/analytics-browser';
amplitude.init(import.meta.env.VITE_AMPLITUDE_API_KEY, {
defaultTracking: {
sessions: true,
pageViews: false, // manual control
formInteractions: false,
fileDownloads: true,
},
logLevel: import.meta.env.DEV
? amplitude.Types.LogLevel.Debug
: amplitude.Types.LogLevel.Warn,
flushIntervalMillis: 10000,
flushQueueSize: 30,
serverUrl: undefined, // EU: 'https://api.eu.amplitude.com'
});
export { amplitude };
For CDN without bundler:
<script type="text/javascript">
!function(){"use strict";!function(e,t){var r=e.amplitude||{_q:[],_iq:{}};if(r.invoked)e.console&&console.error&&console.error("Amplitude snippet has been loaded.");else{r.invoked=!0;var n=t.createElement("script");n.type="text/javascript",n.integrity="sha384-PPfHw2ILiMEr3WZDN6DpXDT0H5MkALzORQB9jAbWCEBpI6kU0MXVIRlzEpLDMo0e",n.crossOrigin="anonymous",n.async=!0,n.src="https://cdn.amplitude.com/libs/analytics-browser-2.10.1-min.js.gz",n.onload=function(){e.amplitude.runQueuedFunctions||console.log("[Amplitude] Failed to load SDK")};var s=t.getElementsByTagName("script")[0];s.parentNode.insertBefore(n,s);function v(e,t){e.prototype[t]=function(){return this._q.push({name:t,args:Array.prototype.slice.call(arguments,0)}),this}}var o=function(){this._q=[],this._q.push(arguments)};v(o,"add"),v(o,"append"),v(o,"clearAll"),v(o,"prepend"),v(o,"set"),v(o,"setOnce"),v(o,"unset"),v(o,"preInsert"),v(o,"postInsert"),v(o,"remove"),v(o,"getUserProperties");var u=function(){return this._q=[],this};["setProductId","setQuantity","setPrice","setRevenue","setRevenueType","setEventProperties","setGroups","setGroupProperties","setTime","setLocationId","setReceipt","setReceiptSig","setReceiptType","setUserData"].forEach(function(e){v(u,e)});r.Revenue=u;var l=["getDeviceId","setDeviceId","getSessionId","setSessionId","getUserId","setUserId","clearUserProperties","setUserProperties","addUserProperties","setOptOut","logEvent","identify","groupIdentify","setGroup","getBrowserType","logRevenue","logRevenueV2","regenerateDeviceId","logEventWithTimestamp","logEventWithGroups","setVersionName","init","removeEventType"].concat(["runQueuedFunctions"]);for(var p=0;p<l.length;p++){var c=l[p];r[c]=function(e){return function(){var t=[e].concat(Array.prototype.slice.call(arguments,0));return r._q.push(t),r}}(c)}e.amplitude=r}}(window,document)}();
amplitude.init('YOUR_API_KEY');
</script>
Event Tracking
Amplitude uses an event model with arbitrary properties. Event naming follows Noun Verb or Subject Action:
import { amplitude } from '@/analytics/amplitude';
import { track, Identify, identify, Revenue, revenue } from '@amplitude/analytics-browser';
// Page view
track('Page Viewed', {
page_path: window.location.pathname,
page_title: document.title,
page_type: 'product_listing',
});
// CTA click
track('CTA Clicked', {
cta_text: 'Try for Free',
cta_position: 'header',
page_section: 'hero',
});
// Form completion
track('Form Completed', {
form_type: 'lead',
fields_filled: ['name', 'email', 'phone'],
time_to_complete_seconds: 45,
});
// Product view
track('Product Viewed', {
product_id: 'SKU-001',
product_name: 'Professional Plan',
product_category: 'subscription',
price: 2990,
currency: 'RUB',
});
Identification and User Properties
import { Identify, identify, setUserId } from '@amplitude/analytics-browser';
// After login
function onUserAuthenticated(user: {
id: string;
email: string;
plan: 'free' | 'pro' | 'enterprise';
company?: string;
createdAt: string;
}) {
setUserId(user.id);
const identifyEvent = new Identify();
identifyEvent.set('email', user.email);
identifyEvent.set('plan', user.plan);
identifyEvent.set('company', user.company ?? '');
identifyEvent.setOnce('signup_date', user.createdAt);
identifyEvent.add('login_count', 1);
identify(identifyEvent);
}
// Reset on logout
function onUserLoggedOut() {
amplitude.reset(); // clears userId and deviceId
}
Revenue Tracking
import { Revenue, revenue } from '@amplitude/analytics-browser';
function trackPurchase(order: {
productId: string;
productName: string;
price: number;
quantity: number;
orderId: string;
}) {
const revenueEvent = new Revenue()
.setProductId(order.productId)
.setPrice(order.price)
.setQuantity(order.quantity)
.setRevenue(order.price * order.quantity)
.setRevenueType('purchase')
.setEventProperties({
order_id: order.orderId,
product_name: order.productName,
});
revenue(revenueEvent);
}
Plugin for Click Auto-tracking
Amplitude supports plugins. You can write a plugin to automatically track clicks on all elements with data-track:
// src/analytics/plugins/autotrack.ts
import type { BrowserClient, Plugin } from '@amplitude/analytics-browser';
export const autoTrackPlugin = (): Plugin => ({
name: 'auto-track-plugin',
type: 'enrichment',
setup: async (_config, client: BrowserClient) => {
document.addEventListener('click', (e) => {
const target = (e.target as HTMLElement).closest('[data-track]');
if (!target) return;
const eventName = target.getAttribute('data-track') ?? 'Element Clicked';
const props = target.dataset as Record<string, string>;
client.track(eventName, {
element_text: target.textContent?.trim().substring(0, 100),
element_class: target.className,
...props,
});
});
},
});
// Installation
amplitude.add(autoTrackPlugin());
Server-side via HTTP API v2
// app/Services/AmplitudeService.php
class AmplitudeService
{
private string $apiKey;
private string $endpoint = 'https://api2.amplitude.com/2/httpapi';
public function __construct()
{
$this->apiKey = config('services.amplitude.api_key');
}
public function track(string $userId, string $eventType, array $eventProperties = []): bool
{
$payload = [
'api_key' => $this->apiKey,
'events' => [[
'user_id' => $userId,
'event_type' => $eventType,
'event_properties' => $eventProperties,
'time' => (int) (microtime(true) * 1000),
'insert_id' => uniqid('srv_', true),
'platform' => 'web',
]],
];
$response = Http::timeout(5)->post($this->endpoint, $payload);
// Amplitude returns { "code": 200, "events_ingested": 1, ... }
return $response->ok() && ($response->json('code') === 200);
}
public function trackBatch(array $events): array
{
// Batch up to 10 events per request
$chunks = array_chunk($events, 10);
$results = [];
foreach ($chunks as $chunk) {
$response = Http::timeout(10)->post($this->endpoint, [
'api_key' => $this->apiKey,
'events' => $chunk,
]);
$results[] = $response->json();
}
return $results;
}
}
Cohorts API for Data Export
Amplitude allows exporting user cohorts to CRM or email systems:
# Get cohorts list
curl -X GET 'https://amplitude.com/api/3/cohorts' \
-u 'API_KEY:SECRET_KEY'
# Export cohort (async)
curl -X GET 'https://amplitude.com/api/5/cohorts/export/download?id=COHORT_ID&props=1' \
-u 'API_KEY:SECRET_KEY' \
--output cohort.csv
Session Replay Configuration
Amplitude Session Replay writes DOM snapshots without capturing personal data:
import { sessionReplayPlugin } from '@amplitude/plugin-session-replay-browser';
amplitude.add(sessionReplayPlugin({
sampleRate: 0.1, // 10% of sessions
privacyConfig: {
blockSelector: ['[data-private]', 'input[type="password"]', '.sensitive'],
defaultBlockLevel: 'medium', // hides input text
},
}));
Timeline
Basic setup with key events — 1 day. Full identify, revenue, plugins setup — 2–3 days. Server-side integration and cohort configuration — 1–2 more days.







