---
title: "How to add product analytics to your app with Lovable"
description: "Connect Lovable to Amplitude, put your API key in .env, have Lovable install the SDK, review its changes, and save the rules as project knowledge."
canonical: "https://amplitude.com/en-us/build/lovable-product-analytics"
---

# How to add product analytics to your app with Lovable

Connect Lovable to Amplitude, put your API key in .env, have Lovable install the SDK, review its changes, and save the rules as project knowledge.

Source: https://amplitude.com/en-us/build/lovable-product-analytics

---

# How to add product analytics to your app with Lovable

Connect Lovable to Amplitude's MCP servers, put your API key where the browser can read it, and hand Lovable one prompt that installs the SDK the docs recommend. Then review its changes, add one event that matches your taxonomy, and save the rules as project knowledge. About 15 minutes, all copy-paste.

- Lovable
- React
- TanStack Start
- Amplitude MCP
- 15 min

Chris Tam · Last updated 6 October 2026

Lovable builds full-stack web apps from chat prompts. It can add [product analytics](https://amplitude.com/amplitude-analytics) to your app the same way, as long as it reads current Amplitude docs and puts your API key where the browser can reach it.

In this tutorial, you'll connect Lovable to Amplitude, add your API key, have Lovable install the SDK, review its changes, and save the rules as project knowledge.

## What you'll build

A Lovable project connected to the Amplitude MCP server and the Docs MCP server, an app instrumented with `@amplitude/unified` and initialized only in the browser, signed-in users identified by their auth user ID, one `Project Created` event named to match your existing taxonomy, and project knowledge that keeps Lovable on those conventions. By the end you'll see live events in your Amplitude project.

## Prerequisites

- A Lovable account and a project with edit access. Pages behind a sign-in assume Lovable's built-in auth (Cloud) or your own connected Supabase project.
- An Amplitude account with access to a project, and that project's API key. In Amplitude, go to Settings > Projects > your project > General.

No Amplitude account yet? A free account is enough for this tutorial; nothing here needs a paid Amplitude plan. [Sign up for free](https://app.amplitude.com/signup) to get your project API key.

## 1. Connect Lovable to Amplitude

Lovable calls these chat connectors. They're personal to you, they work in the project chat while you build, and they never ship in your published app. Add two.

The first is the Amplitude connector, which reads your projects and tracking plan with your own Amplitude permissions. These steps follow Lovable's current Connectors screen; the [Amplitude setup guide for Lovable](https://amplitude.com/docs/amplitude-ai/amplitude-mcp/lovable) covers the same OAuth connection:

1. In Lovable, open **Connectors** and search for `Amplitude`.
2. Click **Add connection**. If Lovable asks for a connection type, choose **Chat connector**.
3. Complete the Amplitude OAuth authorization.

The second is the public [Docs MCP server](https://amplitude.com/docs/amplitude-ai/docs-mcp-server), which serves current Amplitude documentation. Add it as a custom MCP server:

1. In **Connectors**, click the **+** button at the top right of the catalog and choose **MCP server**.
2. Set **Server name** to `Amplitude Docs`.
3. Set **Server URL** to `https://amplitude.com/docs/api/mcp`.
4. Choose **No authentication**, since the Docs server is public, then click **Add server**.

Check both in the project chat:

Prompt for Lovable

```text
What Amplitude projects can I access? Then use the Amplitude Docs
connector to search the docs for "Browser Unified SDK" and tell me which
page you found.
```

A list of your projects plus a docs page title means both connectors work.

**Why.** The Amplitude connector isn't an ingestion endpoint and never sends your app's events. It's how Lovable reads your taxonomy and checks results; the SDK still does the sending. The Docs connector is what stops Lovable from installing a package it remembers instead of the one the Quickstart recommends today.

## 2. Add your API key to .env

This is the step Lovable makes easy to get wrong. Lovable has a **Secrets** manager, and it's the wrong place for this key. Secrets only reach your backend functions, never the browser, and Lovable rejects any name that starts with `VITE_` there. Browser values belong in the project's `.env` file with a `VITE_` prefix, which Lovable builds into the client bundle.

Add this line to `.env` at the project root:

.env

```sh
VITE_AMPLITUDE_API_KEY=your-project-api-key
```

On a paid Lovable plan, open the **Code** tab, edit `.env`, and save. On the Free plan the code editor is read-only, so either edit `.env` in your synced GitHub repository, or ask Lovable in the project chat to add that exact line to `.env`. If you paste the key into the chat, Lovable may also save it as a project secret or offer to set up a connector. That copy is harmless but unused, because secrets never reach the browser. The `.env` line is what your app reads.

**Why.** Lovable commits `.env` with your project so previews and published builds can read `VITE_` values. Don't add `.env` to `.gitignore`; Lovable's docs warn that it breaks the preview. Shipping this key is fine: the Amplitude project API key is public and its scope is limited to the minimum needed to ingest data, so it isn't a secret the way a server credential is.

## 3. Run the install prompt

Paste this prompt into the project chat. If you want to approve the plan before Lovable writes code, send it in **Plan** mode, then approve the plan to build it. The prompt points Lovable at the Quickstart through the Docs connector instead of its memory, and pins the decisions agents most often get wrong.

Prompt for Lovable

```text
Install Amplitude analytics in this project.

Before writing code:
1. Use the Amplitude Docs connector. Get the page
   "get-started/amplitude-quickstart" and use the npm install path it
   recommends for browser apps. Do not pick a package from memory.
2. Use the Amplitude connector. List my Amplitude projects and ask me
   which project this app should send to.
3. Tell me which stack this project is on (React + Vite or TanStack
   Start), and show me your plan before editing files.

Then:
- Read the API key from import.meta.env.VITE_AMPLITUDE_API_KEY. It is
  already in .env. Never hardcode the key, and do not store it in Secrets.
- Create src/lib/amplitude.ts. Call initAll there exactly once, and only
  in the browser: guard it with typeof window !== "undefined", because
  pages can render on the server. Import that file once from the app's
  root, not from a component body or a useEffect in every page.
- Set sessionReplay.sampleRate to 1 and tell me that session replay is on
  and how to turn it off.
- Rely on autocapture for page views. Do not add manual page view tracking.
- If the app has login, subscribe once to the auth client's
  onAuthStateChange, from the root component. Call setUserId with the
  signed-in user's ID, and call reset() only on the SIGNED_OUT event.
- Do not add any custom events yet.

When you finish, list every file you changed and why.
```

Lovable comes back with the docs page it read, a project question, and a plan. Pick the project, approve the plan, and let it build.

## 4. Review what Lovable changed

Review the diff before you test. Open **History**, find the version Lovable just created, and choose **View code changes** from its **More actions** menu. [Version history](https://docs.lovable.dev/features/projects/history) also lets you revert the whole change if it went sideways. These are the mistakes that show up most often, and each takes seconds to spot:

1. **Package.** For browser apps installed from npm, the Quickstart recommends `@amplitude/unified`. Anything else deserves a question.
2. **API key.** Search the code for the literal key. It should appear only in `.env`, never in a source file.
3. **Server rendering.** New Lovable projects use TanStack Start, which renders pages on the server. `initAll` must sit behind a `typeof window !== "undefined"` check, or the server tries to run browser-only code.
4. **Init location.** One `initAll` call, in `src/lib/amplitude.ts`. Not inside a page component or an effect that runs on every route.
5. **Duplicate page views.** No hand-written `track("Page Viewed")` next to autocapture, which tracks page views by default.
6. **Logout.** `reset()` runs on `SIGNED_OUT` only. Calling it on every auth event gives each visitor a new device ID on every load.
7. **Session replay.** `@amplitude/unified` records sessions when `sessionReplay.sampleRate` is above 0. Keep it, or set it to `0` on purpose.

A correct init file looks like this:

src/lib/amplitude.ts

```typescript
import { initAll } from "@amplitude/unified";

if (typeof window !== "undefined") {
  initAll(import.meta.env.VITE_AMPLITUDE_API_KEY, {
    sessionReplay: {
      sampleRate: 1, // set to 0 to turn session replay off
    },
  });
}
```

And a correct identity hook, which works with the auth client Lovable generated for your project:

src/lib/amplitude-identity.ts

```typescript
import type { SupabaseClient } from "@supabase/supabase-js";
import { reset, setUserId } from "@amplitude/unified";

export function syncAmplitudeIdentity(supabase: SupabaseClient) {
  const { data } = supabase.auth.onAuthStateChange((event, session) => {
    if (event === "SIGNED_OUT") {
      reset();
      return;
    }
    if (session?.user) {
      setUserId(session.user.id);
    }
  });

  return () => data.subscription.unsubscribe();
}
```

Lovable should call it once, from the root component, with the Supabase client the project already uses:

root component (inside the component body)

```typescript
useEffect(() => syncAmplitudeIdentity(supabase), []);
```

**Why.** The auth user ID is a long UUID string, so it clears Amplitude's 5-character minimum for user IDs. Using that same ID everywhere, including in any backend function that sends events later, keeps one person from showing up as two users.

If something fails the review, ask Lovable to fix it in the same chat:

Prompt for Lovable

```text
Move the Amplitude init out of the page component into
src/lib/amplitude.ts, guard it with typeof window !== "undefined", and
read the key from import.meta.env.VITE_AMPLITUDE_API_KEY instead of the
literal string. List the files you changed.
```

## 5. Add an event that matches your taxonomy

This is where the Amplitude connector earns its setup. Ask Lovable to check what already exists in Amplitude before it names anything.

Prompt for Lovable

```text
I want to track when a user creates a project, with the template they
picked as a property.

1. Use the Amplitude connector to list the existing events and event
   properties in the project we picked.
2. If an event for this already exists, use its exact name and property
   names. If not, propose a name that matches the casing of the existing
   events, and wait for me to confirm it.
3. Import track from "@amplitude/unified" and add one track call in the
   create-project handler, after the project is saved, not in a render or
   an effect.
```

If your tracking plan uses Title Case with spaces, Lovable should propose `Project Created`, not `projectCreated` or `project_created`. Once you confirm, it adds a single call in the handler:

src/components/CreateProjectDialog.tsx (inside the submit handler, after the save succeeds)

```typescript
import { track } from "@amplitude/unified";

track("Project Created", { template });
```

**MCP.** Lovable can also add the new event to your tracking plan through the Amplitude connector, if your Amplitude role has the **Use MCP (write)** permission and the Update Tracking Plan permission in Amplitude Data. Ask it to create the event as planned, so the tracking plan knows about `Project Created` before the first one arrives.

## Verify it worked

Open your app in its own browser tab, sign in, create a project, then check in this order:

1. **Network tab.** Open DevTools, filter for `api2.amplitude.com`, and look for a `POST` to `/2/httpapi` returning `200`.
2. **Ingestion Debugger.** In Amplitude, click **Data**, select **Sources**, then open the **Ingestion Debugger** tab. The successful requests and the events and identify counts charts should show your uploads.
3. **User Profiles.** Go to **Users > User Profiles** and search the user ID from your app's auth users list. `[Amplitude] Page Viewed` and `Project Created` appear in the event stream within ten seconds to a minute. Click `Project Created` to confirm the `template` value.
4. **Ask Lovable.** With the Amplitude connector added, ask it to check the data for you:

Prompt for Lovable

```text
Using the Amplitude connector, look up my user profile in this project
and tell me whether "Project Created" arrived in the last hour and which
template values it has.
```

## Troubleshooting

### No requests to api2.amplitude.com in the Network tab

The key is undefined in the browser. Confirm `.env` has `VITE_AMPLITUDE_API_KEY` with the `VITE_` prefix, that it isn't only in Secrets, and that `.env` isn't in `.gitignore`. An ad blocker can also drop the requests; test once with it turned off.

### The preview shows "window is not defined" or a blank page

`initAll` runs during server rendering. Move it into `src/lib/amplitude.ts` behind the `typeof window !== "undefined"` check from step 4.

### Lovable installed a different package than the Quickstart names

It skipped the docs lookup. Ask it to get `get-started/amplitude-quickstart` through the Amplitude Docs connector and redo the install from that page.

### Events show in the Network tab but not in your project

The key belongs to a different project than the one you picked, or it's an EU project sending to the US endpoint. Compare the key in `.env` with Settings > Projects > your project > General, and set `serverZone: "EU"` in `initAll` for EU projects.

### Every page load shows up as a new user

`reset()` runs on more than `SIGNED_OUT`, so each load gets a fresh device ID. Limit it to the sign-out event, as in the identity hook in step 4.

### Lovable says it has no Amplitude tools, or OAuth never finishes

Check **Connectors** to see that both connections exist. During OAuth, sign in to only one Amplitude organization; signing in to several can break authentication. If it still fails, remove the Amplitude connection and add it again. If **MCP server** is greyed out, a workspace admin has turned off custom MCP servers.

## Save the rules as project knowledge

Lovable reads **project knowledge** on every message, so rules you put there apply to every later edit without the long prompt. Open **Project settings > Knowledge** and add this:

Prompt for Lovable

```text
Analytics (Amplitude)
- Look up Amplitude SDK usage with the Amplitude Docs connector before
  writing analytics code. Never install or import Amplitude packages from
  memory.
- Before adding a track call, list existing events with the Amplitude
  connector and reuse existing event and property names. Match the
  existing casing. Ask before creating a new event name.
- The SDK is initialized once in src/lib/amplitude.ts, behind
  typeof window !== "undefined". Never call initAll anywhere else.
- The API key is VITE_AMPLITUDE_API_KEY in .env. Never hardcode it and
  never move it to Secrets.
- Page views come from autocapture. Never add manual page view tracking.
- Identity comes from the auth user ID through onAuthStateChange.
  Call reset() only on SIGNED_OUT.
- Track user actions in event handlers after the action succeeds, not in
  effects or render paths.
- Import track from "@amplitude/unified".
```

Project knowledge holds up to 10,000 characters. If your project syncs to GitHub, Lovable also reads a root-level `AGENTS.md`, so you can keep the same rules there instead and review changes to them like any other file.

## What this unlocks

- [Session replay](https://amplitude.com/session-replay), with `sampleRate` above 0, lets you watch the session where `Project Created` fired, or the one where someone opened the dialog and never did.
- [Heatmaps](https://amplitude.com/heatmaps), built from those same session replays, show where people clicked on the new-project screen before they created one.
- [Feature Experiment](https://amplitude.com/amplitude-experiment) can test a new template picker with `Project Created` as the success metric, and the `experiment()` client is already inside `@amplitude/unified`.
- [Guides and surveys](https://amplitude.com/guides-and-surveys) can nudge people who signed up but never fired `Project Created`.

One integration; everything else reads from the same events.

## Next steps

[Web frameworksAdd product analytics to a React appWhat the correct browser install looks like, file by file, so you can check Lovable's work against it.](/build/react-product-analytics)[AI coding toolsAdd product analytics to your app with Claude CodeThe same workflow in a terminal agent, with the rules saved in CLAUDE.md.](/build/claude-code-product-analytics)[AI coding toolsAdd analytics to your app with Codex CLIThe same workflow in OpenAI's Codex CLI, with the rules saved in AGENTS.md.](/build/codex-cli-analytics)

Reference docs

[Connect Amplitude MCP to Lovable →](https://amplitude.com/docs/amplitude-ai/amplitude-mcp/lovable)[Amplitude MCP server →](https://amplitude.com/docs/amplitude-ai/amplitude-mcp)[Docs MCP server →](https://amplitude.com/docs/amplitude-ai/docs-mcp-server)[Amplitude Quickstart →](https://amplitude.com/docs/get-started/amplitude-quickstart)[Browser Unified SDK →](https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk)[Debug analytics →](https://amplitude.com/docs/analytics/debug-analytics)

Amplitude is the leading [all-in-one analytics platform](https://amplitude.com/) for building better products. Product and engineering teams use Amplitude to connect [product analytics](https://amplitude.com/amplitude-analytics) and [web analytics](https://amplitude.com/web-analytics) with [session replay](https://amplitude.com/session-replay), [heatmaps](https://amplitude.com/heatmaps), [experimentation](https://amplitude.com/amplitude-experiment), [feature flags](https://amplitude.com/feature-management), and [guides and surveys](https://amplitude.com/guides-and-surveys) in one unified workflow, with [AI agents](https://amplitude.com/ai-agents) working across all of it. Learn how Amplitude is building [self-improving products](https://amplitude.com/self-improving-products) with [Wave](https://amplitude.com/wave), helping teams turn product data into PRs.

For agents

[View raw .md](/build/lovable-product-analytics.md)[llms.txt](/llms.txt)

## Ship the instrumentation, then read the data

Once events are flowing, Amplitude turns them into funnels, retention curves, and session replays without any further setup.

[Create a free account](https://app.amplitude.com/signup)[Browse all Build tutorials](https://amplitude.com/build)
