Skip to main content
RapidDev - Software Development Agency
lovable-integrationsEdge Function Integration

How to Integrate Lovable with Amplitude

Add Amplitude product analytics to a Lovable app by installing the @amplitude/analytics-browser SDK for client-side event and user tracking, and creating a Supabase Edge Function that calls Amplitude's HTTP API v2 for server-side event streaming. Store your Amplitude API Key as VITE_AMPLITUDE_API_KEY for the frontend and use Cloud → Secrets for any server-side credentials.

What you'll learn

  • How to install and initialize the Amplitude Browser SDK in a Lovable Vite+React project
  • How to implement user identification, group analytics, and event tracking with typed properties
  • How to create a Supabase Edge Function that streams events to Amplitude's HTTP API v2 for server-side tracking
  • How to build Amplitude Charts and Cohorts for retention analysis and feature adoption measurement
  • How to use Amplitude's Experiment feature for A/B testing from a Lovable app
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Intermediate20 min read35 minutesAnalyticsMarch 2026RapidDev Engineering Team
TL;DR

Add Amplitude product analytics to a Lovable app by installing the @amplitude/analytics-browser SDK for client-side event and user tracking, and creating a Supabase Edge Function that calls Amplitude's HTTP API v2 for server-side event streaming. Store your Amplitude API Key as VITE_AMPLITUDE_API_KEY for the frontend and use Cloud → Secrets for any server-side credentials.

Adding Amplitude Product Analytics to Your Lovable App

Amplitude is the analytics platform built for retention-obsessed product teams. While Google Analytics answers 'where do my users come from?', Amplitude answers 'which users come back tomorrow, next week, and next month — and what did they do differently?' Its behavioral cohort engine lets you define any segment of users by what they did (or did not do) and then analyze how that group behaves over time. For Lovable app builders, Amplitude answers the questions that determine product-market fit: which onboarding paths lead to retained users, which features separate power users from churned users, and which new feature launches actually changed user behavior.

Amplitude's integration with Lovable follows a dual-layer architecture that matches the platform's security model. The @amplitude/analytics-browser SDK installs as an npm package and handles client-side tracking — it automatically captures device type, location, referrer, and session data alongside your custom events, making each event richer than manually crafted payloads. For server-side events that must be captured regardless of browser state — Stripe payment confirmations, scheduled job results, email delivery events — a Supabase Edge Function calls Amplitude's HTTP API v2 directly using an API key stored in Cloud → Secrets.

Note that Amplitude also ships as a personal MCP connector in Lovable — when you connect it via Settings → Personal Connectors → Amplitude, the Lovable AI agent can read your Amplitude data during the building process to generate code that aligns with your existing event taxonomy. This is separate from the runtime integration described in this guide, which adds actual analytics tracking to your deployed application. Lovable's security infrastructure blocks approximately 1,200 hardcoded API keys daily and holds SOC 2 Type II certification — your Amplitude API key must live in Cloud → Secrets, accessed in Edge Functions via Deno.env.get().

Integration method

Edge Function Integration

Amplitude integrates with Lovable through the @amplitude/analytics-browser npm package for client-side tracking and a Supabase Edge Function that calls Amplitude's HTTP API v2 for server-side event streaming. The browser SDK handles user identification, session replay (on paid plans), and automatic event enrichment. The Edge Function proxy enables backend event tracking — payment completions, webhook-triggered actions — using your Amplitude API key stored in Cloud → Secrets.

Prerequisites

  • A Lovable account with an existing project that has Supabase and user authentication configured
  • An Amplitude account — free Starter plan available at amplitude.com with up to 10 million events per month
  • Your Amplitude API Key from Settings → Projects → your project → General (not the Secret Key)
  • For server-side HTTP API calls: the same API key is used — Amplitude's HTTP API v2 authenticates with the API key in the request body
  • Basic understanding of what analytics events you want to track before writing code — an event taxonomy plan prevents fragmented data

Step-by-step guide

1

Create an Amplitude project and configure your API key in Lovable Secrets

Start by setting up your Amplitude project and getting the credentials you need. Log in to your Amplitude account at app.amplitude.com. If you are creating a new project, click 'Create Project' from the home screen — give it the name of your Lovable app and select 'Web' as the platform. If you already have an Amplitude project, navigate to Settings (gear icon in the bottom-left sidebar) and select Projects from the left panel. Click on your project name to open its settings. In the General tab, you will find your API Key — a 32-character hexadecimal string. This is the public project identifier used to authenticate your events. Note that Amplitude also has a Secret Key on this page, which is used for specific management API calls. For standard event tracking (both client-side SDK and HTTP API v2 server-side), only the API Key is needed. Copy the API Key. Now go to your Lovable project in the browser. Click the + icon next to the Preview button to open the Cloud tab. Click Secrets in the panel. Click Add secret. Add VITE_AMPLITUDE_API_KEY with your API key value — the VITE_ prefix makes it accessible as import.meta.env.VITE_AMPLITUDE_API_KEY in your React components. Also add AMPLITUDE_API_KEY with the same value for use in Edge Functions via Deno.env.get('AMPLITUDE_API_KEY'). Click Save for each secret. In Amplitude's settings, also configure your project's User Property schema. Go to Settings → Project Settings → Schema and review the default user properties. This is also a good time to enable Session Replay if you are on a paid plan — it provides visual session recordings alongside your event data, giving valuable context for behavioral analysis without any additional code.

Pro tip: Create a separate Amplitude project for development and production from the start. Use the development project's API key in your local .env.local file and the production key in Lovable Cloud Secrets. This prevents development test events from contaminating your production user data and retention metrics.

Expected result: VITE_AMPLITUDE_API_KEY and AMPLITUDE_API_KEY are stored in Lovable Cloud Secrets. Your Amplitude project exists and the API Key is saved. The Amplitude dashboard shows your project configured with the correct platform settings.

2

Install the Amplitude Browser SDK and create the analytics utility

Install the @amplitude/analytics-browser package and create a centralized Amplitude utility module that all components import. This utility handles the three core Amplitude patterns: initialization with your API key and configuration options, user identification when a user logs in, and event tracking with typed properties. Amplitude's Browser SDK v2 (the current major version) uses a modular architecture — import only the functions you need from @amplitude/analytics-browser to keep your bundle size minimal. The most important functions are init (initialization), identify (user identification), setUserId (link device to authenticated user), and track (event tracking). The SDK automatically captures device information, platform, OS version, app version (from your package.json), and session data — you do not need to add these to every event manually. Configure the SDK with production-appropriate settings: disable autocapture of all events initially (Amplitude's autocapture can generate noisy data — enable specific autocapture events intentionally), set the logLevel to LogLevel.Warn in production, and configure the flushIntervalMillis to control how frequently events are batched and sent to Amplitude's servers. A lower interval means more real-time data but more HTTP requests; 10 seconds is a good balance for most apps. The identify pattern in Amplitude is slightly different from Mixpanel. Instead of an explicit identify() call with user properties, Amplitude uses setUserId() to link the device to the authenticated user, then uses the Identify class to set user properties. The setUserId should be called immediately when the user's Supabase session is established. When the user logs out, call setUserId(undefined) to reset the association between the device and the logged-out user — this prevents the next user on the same device from inheriting the previous user's identity.

Lovable Prompt

Install @amplitude/analytics-browser and create a src/lib/amplitude.ts utility. Export: init() that initializes Amplitude with VITE_AMPLITUDE_API_KEY, identify(userId: string, properties: object) that calls setUserId and sets user properties using the Identify class, track(eventName: string, properties?: object) that calls Amplitude's track function, and reset() that calls setUserId(undefined) and reset(). Handle missing API key gracefully.

Paste this in Lovable chat

src/lib/amplitude.ts
1// src/lib/amplitude.ts
2import * as amplitude from '@amplitude/analytics-browser';
3import { Identify } from '@amplitude/analytics-browser';
4
5const API_KEY = import.meta.env.VITE_AMPLITUDE_API_KEY;
6let initialized = false;
7
8export function initAmplitude() {
9 if (!API_KEY) {
10 console.warn('Amplitude API key not configured. Analytics disabled.');
11 return;
12 }
13 amplitude.init(API_KEY, {
14 logLevel: import.meta.env.DEV ? amplitude.Types.LogLevel.Debug : amplitude.Types.LogLevel.Warn,
15 autocapture: {
16 sessions: true,
17 pageViews: true,
18 formInteractions: false,
19 fileDownloads: false,
20 },
21 flushIntervalMillis: 10000,
22 });
23 initialized = true;
24}
25
26export function identify(userId: string, properties?: Record<string, unknown>) {
27 if (!initialized) return;
28 amplitude.setUserId(userId);
29 if (properties) {
30 const identifyEvent = new Identify();
31 Object.entries(properties).forEach(([key, value]) => {
32 identifyEvent.set(key, value as string | number | boolean);
33 });
34 amplitude.identify(identifyEvent);
35 }
36}
37
38export function track(eventName: string, properties?: Record<string, unknown>) {
39 if (!initialized) return;
40 amplitude.track(eventName, properties);
41}
42
43export function reset() {
44 if (!initialized) return;
45 amplitude.setUserId(undefined);
46 amplitude.reset();
47}

Pro tip: Amplitude's Browser SDK v2 batches events and sends them in groups to reduce network overhead. Events are flushed when the batch reaches 30 events, when the flush interval elapses, or when the user navigates away from the page. In development, you can force immediate flushing with amplitude.flush() to verify events are sent.

Expected result: The @amplitude/analytics-browser package is installed. The amplitude.ts utility initializes correctly when VITE_AMPLITUDE_API_KEY is set. The Amplitude app shows a green 'Data arriving' indicator in the project dashboard after the first events are sent.

3

Implement user identification and feature event tracking

With the Amplitude utility in place, add identification and event tracking at the key behavioral moments in your application. The most important events to track are the ones that predict retention — the actions that separate users who stay from users who leave. For most SaaS apps, these are completing onboarding, using a core feature within the first session, and returning within 3 days. For user identification, hook into your Supabase auth state change event — the same pattern used for Mixpanel. When the 'SIGNED_IN' event fires, call your identify function with the Supabase user ID and key user properties: email (if you want to enable email-based user lookup in Amplitude), plan, account creation date, and any custom attributes relevant to your product. Amplitude's user properties persist across sessions — once you set a user's plan, it is available on all subsequent events without needing to pass it explicitly. For event tracking, follow a naming convention that makes Amplitude's charts readable: use subject-verb pairs in title case ('Project Created', 'Export Downloaded', 'Subscription Upgraded'). Include contextual properties on each event — the current state of the user when the event happened. For a 'Feature Used' event, include: which feature, how many times the user has used it before (to distinguish first-time versus repeat usage), and the user's current plan. These properties enable Amplitude's property filter in charts, allowing you to slice any chart by any event property. Amplitude's Group Analytics feature (available on paid plans) lets you analyze events at the organization or account level rather than the individual user level — useful for B2B apps where you care about company-level retention. To use groups, call setGroup() with the group type and group ID when a user is associated with an organization in your app.

Lovable Prompt

Add Amplitude tracking to the authentication flow and main features. In the auth state change handler, call identify() with the user's Supabase ID, email, and plan when SIGNED_IN fires. Track 'Signed Up' on registration with a signup_method property. Track 'Feature Used' with feature_name, is_first_use, and user_plan properties at each key feature interaction. Call reset() on SIGNED_OUT. Import all functions from src/lib/amplitude.ts.

Paste this in Lovable chat

src/hooks/useAmplitudeTracking.ts
1// src/hooks/useAmplitudeTracking.ts
2import { useEffect } from 'react';
3import { supabase } from '@/integrations/supabase/client';
4import { identify, track, reset } from '@/lib/amplitude';
5
6export function useAmplitudeTracking() {
7 useEffect(() => {
8 const { data: { subscription } } = supabase.auth.onAuthStateChange(
9 async (event, session) => {
10 if (event === 'SIGNED_IN' && session?.user) {
11 const user = session.user;
12 identify(user.id, {
13 email: user.email,
14 plan: 'free', // fetch from your users/profiles table
15 created_at: user.created_at,
16 signup_method: user.app_metadata?.provider ?? 'email',
17 });
18 track('Session Started');
19 }
20 if (event === 'SIGNED_OUT') {
21 track('Session Ended');
22 reset();
23 }
24 }
25 );
26 return () => subscription.unsubscribe();
27 }, []);
28}
29
30// Helper for feature tracking across components
31export function trackFeatureUse(featureName: string, additionalProperties?: Record<string, unknown>) {
32 track('Feature Used', {
33 feature_name: featureName,
34 timestamp: new Date().toISOString(),
35 ...additionalProperties,
36 });
37}

Pro tip: Amplitude's Taxonomy feature (in your project settings) lets you define an official event schema with required properties and expected value types. Enabling it causes the SDK to warn when events are sent without required properties — useful for catching tracking gaps during development.

Expected result: Amplitude's Live Activity stream shows events appearing in real time as you use the app. The Users list shows user profiles being created with the correct identity properties. Feature interactions appear as events with their contextual properties.

4

Create a Supabase Edge Function for Amplitude HTTP API v2

For server-side event tracking — payment completions, email deliveries, scheduled job results, and any event that needs to be recorded regardless of the user's browser state — create a Supabase Edge Function that calls Amplitude's HTTP API v2 directly. This API accepts JSON event payloads and supports batched event uploads, making it efficient for high-volume server-side event streams. Amplitude's HTTP API v2 endpoint is https://api2.amplitude.com/2/httpapi. The request body is a JSON object containing your API key and an array of event objects. Each event object requires an event_type string and either a user_id (for authenticated users) or a device_id (for anonymous tracking). Events can optionally include event_properties (key-value pairs specific to this event), user_properties (updates to the user's profile), and a time field (Unix timestamp in milliseconds — defaults to the current time if omitted). The Edge Function should accept a POST request from your Lovable frontend or from other Edge Functions (such as the Stripe webhook handler) with the event data as a JSON body. Validate the inputs, format them as an Amplitude HTTP API v2 payload, and POST to Amplitude's endpoint. The function reads the API key from Deno.env.get('AMPLITUDE_API_KEY') — never hardcode it. An important consideration for server-side events: the user_id must match the same user_id used in the client-side SDK (the Supabase user UUID). If the IDs do not match, Amplitude creates separate user profiles for the same person, fragmenting their journey across your reports. Always use the Supabase user UUID consistently across both client-side and server-side tracking calls.

Lovable Prompt

Create a Supabase Edge Function called 'amplitude-track' that accepts POST requests with event_type, user_id, optional device_id, optional event_properties, and optional user_properties. Forward the event to Amplitude's HTTP API v2 at https://api2.amplitude.com/2/httpapi using AMPLITUDE_API_KEY from Deno secrets. Support batching by accepting an events array. Return 200 even on Amplitude API failure.

Paste this in Lovable chat

supabase/functions/amplitude-track/index.ts
1// supabase/functions/amplitude-track/index.ts
2import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
3
4const corsHeaders = {
5 'Access-Control-Allow-Origin': '*',
6 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
7};
8
9interface AmplitudeEvent {
10 event_type: string;
11 user_id?: string;
12 device_id?: string;
13 event_properties?: Record<string, unknown>;
14 user_properties?: Record<string, unknown>;
15 time?: number;
16}
17
18serve(async (req) => {
19 if (req.method === 'OPTIONS') {
20 return new Response('ok', { headers: corsHeaders });
21 }
22
23 try {
24 const apiKey = Deno.env.get('AMPLITUDE_API_KEY');
25 if (!apiKey) {
26 console.error('AMPLITUDE_API_KEY not configured');
27 return new Response(JSON.stringify({ success: false }), {
28 status: 200,
29 headers: { ...corsHeaders, 'Content-Type': 'application/json' },
30 });
31 }
32
33 const body = await req.json();
34 // Support both single event and events array
35 const events: AmplitudeEvent[] = Array.isArray(body.events)
36 ? body.events
37 : [{ event_type: body.event_type, user_id: body.user_id, device_id: body.device_id,
38 event_properties: body.event_properties, user_properties: body.user_properties }];
39
40 const validEvents = events.filter(e => e.event_type && (e.user_id || e.device_id));
41 if (validEvents.length === 0) {
42 return new Response(
43 JSON.stringify({ error: 'Each event requires event_type and user_id or device_id' }),
44 { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
45 );
46 }
47
48 const payload = {
49 api_key: apiKey,
50 events: validEvents.map(e => ({ ...e, time: e.time ?? Date.now() })),
51 };
52
53 const response = await fetch('https://api2.amplitude.com/2/httpapi', {
54 method: 'POST',
55 headers: { 'Content-Type': 'application/json', 'Accept': '*/*' },
56 body: JSON.stringify(payload),
57 });
58
59 const result = await response.json();
60 console.log('Amplitude HTTP API response:', response.status, result);
61
62 return new Response(JSON.stringify({ success: true, events_ingested: validEvents.length }), {
63 headers: { ...corsHeaders, 'Content-Type': 'application/json' },
64 });
65 } catch (error) {
66 console.error('Amplitude track error:', error);
67 return new Response(JSON.stringify({ success: false }), {
68 status: 200,
69 headers: { ...corsHeaders, 'Content-Type': 'application/json' },
70 });
71 }
72});

Pro tip: Amplitude's HTTP API v2 supports uploading up to 2,000 events per request. For high-volume server-side tracking (like sending events for all users in a batch job), batch events into groups of up to 2,000 and send them in parallel Edge Function calls rather than one by one.

Expected result: The amplitude-track Edge Function is deployed. Sending a POST request with a valid event_type and user_id results in the event appearing in Amplitude's Live Activity stream. The function handles both single events and batched events arrays.

5

Build Amplitude retention and cohort reports for your app

With tracking implemented, set up the Amplitude reports that provide immediate product insight. The three most valuable reports for a new Lovable app are: a Retention Analysis chart showing day-1, day-7, and day-30 return rates; a User Journey chart showing the common paths through your app after signup; and a Funnel chart measuring onboarding completion rates. For the Retention Analysis, go to Amplitude → Charts → New Chart → Retention Analysis. Set the 'Did event A' condition to your signup event (the event that marks a new user), and set the 'and came back to do event B' condition to any session event (like a pageview or 'Session Started'). Set the date range to the last 90 days. Amplitude calculates what percentage of users from each signup cohort return each subsequent day, week, or month. This chart is the most important early-stage product metric — if day-1 retention is below 30%, focus on onboarding improvements before anything else. For the User Journey report, go to Charts → Pathfinder. Set the starting event to your signup or onboarding completion event. The chart visualizes the most common paths users take through your app in the first session, revealing which features are discovered organically versus which are hidden. Features with unexpectedly low discovery rates may need better UI placement. For the Funnel Analysis, go to Charts → Funnel Analysis and add the events in your critical conversion path — signup → onboarding step 1 → onboarding step 2 → first value action → subscription. The chart shows conversion rates at each step and, crucially, the time each step takes. Long completion times at specific steps often indicate friction points. For complex Amplitude implementations or integrating Amplitude Experiment for A/B testing in your Lovable app, RapidDev's team can help set up the experiment SDK and result analysis workflows.

Pro tip: Amplitude's Compass feature (Dashboard → Compass) automatically analyzes your event data and surfaces the behaviors that most strongly predict retention — it identifies which first-session actions correlate with users returning. Check this weekly as new event data accumulates.

Expected result: Amplitude shows populated Retention Analysis, Pathfinder, and Funnel reports using real data from your Lovable app. The Retention chart shows cohort-based return rates. The Funnel chart identifies the onboarding step with the highest drop-off rate.

Common use cases

Track user retention with behavioral cohort analysis

Instrument user onboarding milestones and weekly product usage events so Amplitude can calculate retention rates. Define a retention cohort as users who performed a 'First Value Action' within 7 days of signup, then compare their 30-day retention against users who did not. This data directly shows whether your onboarding improvements are working and which features drive long-term retention.

Lovable Prompt

Add Amplitude event tracking to measure user retention. Track 'Onboarding Started' when a new user first logs in, 'Onboarding Completed' when they finish setup, 'First Value Action' when they create their first meaningful item, and 'Weekly Active' once per week when they return to the app. Include a user_plan property on all events. Use the Amplitude Browser SDK initialized with VITE_AMPLITUDE_API_KEY.

Copy this prompt to try it in Lovable

Measure feature adoption across user segments

Track every major feature interaction with consistent event names and properties so Amplitude's charts can show feature adoption rates over time. Amplitude's User Composition and Funnel charts reveal which user segments (by plan, acquisition source, or account age) adopt new features fastest, which helps product teams decide which features to invest in and which to deprecate.

Lovable Prompt

Add Amplitude feature adoption tracking. For each major feature in the app, track a '[Feature Name] Used' event when a user activates it, with properties: feature_name, user_plan, days_since_signup, and is_first_use (boolean). Create a src/lib/amplitude.ts utility that exports a trackFeature(featureName: string, properties: object) helper that adds these standard properties automatically.

Copy this prompt to try it in Lovable

Stream server-side payment events via Edge Function

Send payment lifecycle events to Amplitude from the Stripe webhook Edge Function to ensure revenue data is never lost due to browser closures or ad blockers. Amplitude's Revenue LTV charts use purchase events to calculate lifetime value by cohort — server-side tracking guarantees complete data for these critical business metrics.

Lovable Prompt

Create a Supabase Edge Function that sends Amplitude revenue events when Stripe payments succeed. Track 'Revenue Generated' with event properties: revenue (amount in dollars), productId (Stripe price ID), quantity, and revenueType ('purchase'). Use Amplitude's HTTP API v2 with the AMPLITUDE_API_KEY secret. Call this function from the existing Stripe webhook handler after checkout.session.completed events.

Copy this prompt to try it in Lovable

Troubleshooting

Amplitude Live Activity shows no events after installing the SDK

Cause: The Amplitude SDK was not initialized before the first track call, the VITE_AMPLITUDE_API_KEY environment variable is undefined in the build environment, or the SDK is being initialized in a component that renders server-side (not applicable in Vite, but worth checking).

Solution: Verify that initAmplitude() is called in your app root (App.tsx or main.tsx) before any track calls. Check that VITE_AMPLITUDE_API_KEY is set as a build-time environment variable — it must be in the Lovable build environment configuration, not just in Cloud Secrets (Cloud Secrets are only for Edge Functions). Open the browser console and look for Amplitude's initialization log message or the 'Amplitude API key not configured' warning.

User profiles in Amplitude show duplicate users — the same person appears multiple times

Cause: The user_id changes between sessions, or setUserId() is called with a different ID format (email versus UUID) at different points in the code.

Solution: Always use the Supabase user UUID as the Amplitude user_id — never use the user's email address or any other identifier that might be formatted differently in different code paths. Check all places in your app where identify() or setUserId() is called and ensure they all use session.user.id from Supabase. For anonymous users before login, Amplitude assigns a device_id automatically — the profile merge happens when you call setUserId() after login.

Edge Function logs show 'Bad Request' from Amplitude's HTTP API v2

Cause: The event payload is missing required fields — each event must have event_type and either user_id or device_id. The api_key in the request body may be incorrect, or the events array may be empty.

Solution: Check the Amplitude HTTP API v2 response body — it includes a code and error string identifying the exact issue. Common errors: code 400 means validation failed (check event_type and user_id are present), code 413 means the payload exceeds the 20MB limit (reduce batch size), and code 429 means you have exceeded the rate limit. Add logging to print the full API response body in the Edge Function to diagnose the exact issue.

typescript
1// Add to Edge Function to log the full error response:
2const responseText = await response.text();
3console.log('Amplitude API error response:', response.status, responseText);

Amplitude retention charts show much lower retention than expected

Cause: The return event used in the Retention Analysis is too specific — users who return but do not perform that exact action are not counted as retained. Or the retention calculation window does not match how you define a 'retained user'.

Solution: Use a broad return event like 'Session Started' or a pageview event rather than a specific feature action for the retention calculation. Amplitude's retention chart shows 'returned at all' when the return event is broad, or 'returned and did X' when it is specific — make sure you are measuring the right thing. Check the measurement type setting in the Retention chart (N-day versus Unbounded) and ensure it matches your definition of retention.

Best practices

  • Define your event taxonomy before writing any tracking code — create a spreadsheet with event names, descriptions, required properties, and the code location where each event fires. Consistent taxonomy prevents fragmented data that makes Amplitude charts unreadable.
  • Use the Supabase user UUID as the Amplitude user_id everywhere — in both the client-side SDK and the server-side HTTP API calls — to ensure all events for the same person are unified into a single user profile.
  • Store VITE_AMPLITUDE_API_KEY as a build environment variable (accessible in React via import.meta.env) and AMPLITUDE_API_KEY as a Cloud Secret (accessible in Edge Functions via Deno.env.get()). The API key is technically public but using dedicated variables prevents accidental exposure.
  • Call setUserId(undefined) and reset() on logout to prevent the next user on the same device from inheriting the previous user's Amplitude identity — critical for apps used on shared devices or in demos.
  • Return HTTP 200 from analytics Edge Functions even when Amplitude's API returns an error — analytics failures must never cause user-visible errors or fail core application requests.
  • Use Amplitude's SDK's built-in session tracking rather than manually tracking session start/end events — the SDK handles session boundary detection correctly across tab visibility changes and browser lifecycle events.
  • Configure Amplitude's Data schema with required properties for your most important events — this catches tracking gaps during development and ensures consistent data quality as your team adds new tracking calls.
  • Review Amplitude's Compass recommendations weekly — the feature surfaces which behaviors predict retention based on your actual data, providing more reliable guidance than manually analyzing charts.

Alternatives

Frequently asked questions

Is Amplitude free to use with a Lovable app?

Amplitude's Starter plan is free and includes up to 10 million events per month, unlimited users, and all core analytics features including Retention Analysis, Funnel Analysis, and User Journeys. The Growth plan (starting around $49/month) adds behavioral cohorts, unlimited charts, and Session Replay. For most early-stage Lovable apps, the free Starter tier is more than sufficient.

What is the difference between Amplitude's client-side SDK and the HTTP API v2?

The client-side Browser SDK automatically enriches events with device data, session information, and user context gathered from the browser environment. It is the right choice for UI events like button clicks, page views, and feature interactions. The HTTP API v2 is used from Edge Functions for backend events that do not originate in the browser — payment confirmations, email delivery, scheduled job results. Both send events to the same Amplitude property using the same API key.

How does Amplitude's MCP connector in Lovable differ from this runtime integration?

Amplitude's MCP personal connector (configured in Settings → Personal Connectors) gives the Lovable AI agent read access to your Amplitude data during the building process — the AI can look at your existing event taxonomy to generate code that matches your naming conventions. It does not add analytics tracking to your deployed application. This tutorial describes the runtime integration that actually sends events from your live app to Amplitude.

How do I measure which features drive user retention in Amplitude?

Use Amplitude's Retention Analysis chart with the 'Did event A then came back to do event B' setup. Set event A to your signup event and event B to 'any event.' Then use the User Composition breakdown to see which features were used in the first session by users who retained at day 7 versus users who churned. Amplitude's Compass feature also automatically identifies which first-session actions most strongly predict long-term retention.

Can I use Amplitude Experiment for A/B testing in my Lovable app?

Yes. Amplitude Experiment is a separate SDK (@amplitude/experiment-browser) that integrates with your Amplitude analytics project. You define experiments in the Amplitude Experiment dashboard, and the SDK fetches the variant assignment for each user. Track exposure events when users see a variant and analyze results using Amplitude's built-in experiment analysis. The SDK uses the same user_id as your analytics SDK so experiment data is automatically joined with behavioral data.

Why do my server-side events in Amplitude show a different user count than client-side events?

This usually indicates a user_id mismatch between the client and server. The Browser SDK and the HTTP API v2 must use the same user_id string for the same user — the Supabase user UUID. Check that your Edge Function is passing the correct Supabase user ID from the authentication context, not a different identifier like an internal database ID or email address. Mismatched IDs create separate Amplitude user profiles for the same person.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.