Amplitude Analytics Integration

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    847
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    451

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.