Chris Tam · Last updated 6 October 2026
Lovable builds full-stack web apps from chat prompts. It can add product 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 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 covers the same OAuth connection:
- In Lovable, open Connectors and search for
Amplitude. - Click Add connection. If Lovable asks for a connection type, choose Chat connector.
- Complete the Amplitude OAuth authorization.
The second is the public Docs MCP server, which serves current Amplitude documentation. Add it as a custom MCP server:
- In Connectors, click the + button at the top right of the catalog and choose MCP server.
- Set Server name to
Amplitude Docs. - Set Server URL to
https://amplitude.com/docs/api/mcp. - Choose No authentication, since the Docs server is public, then click Add server.
Check both in the project chat:
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:
VITE_AMPLITUDE_API_KEY=your-project-api-keyOn 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.
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 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:
- Package. For browser apps installed from npm, the Quickstart recommends
@amplitude/unified. Anything else deserves a question. - API key. Search the code for the literal key. It should appear only in
.env, never in a source file. - Server rendering. New Lovable projects use TanStack Start, which renders pages on the server.
initAllmust sit behind atypeof window !== "undefined"check, or the server tries to run browser-only code. - Init location. One
initAllcall, insrc/lib/amplitude.ts. Not inside a page component or an effect that runs on every route. - Duplicate page views. No hand-written
track("Page Viewed")next to autocapture, which tracks page views by default. - Logout.
reset()runs onSIGNED_OUTonly. Calling it on every auth event gives each visitor a new device ID on every load. - Session replay.
@amplitude/unifiedrecords sessions whensessionReplay.sampleRateis above 0. Keep it, or set it to0on purpose.
A correct init file looks like this:
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:
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:
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:
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.
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:
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:
- Network tab. Open DevTools, filter for
api2.amplitude.com, and look for aPOSTto/2/httpapireturning200. - 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.
- User Profiles. Go to Users > User Profiles and search the user ID from your app's auth users list.
[Amplitude] Page ViewedandProject Createdappear in the event stream within ten seconds to a minute. ClickProject Createdto confirm thetemplatevalue. - Ask Lovable. With the Amplitude connector added, ask it to check the data for you:
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:
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, with
sampleRateabove 0, lets you watch the session whereProject Createdfired, or the one where someone opened the dialog and never did. - Heatmaps, built from those same session replays, show where people clicked on the new-project screen before they created one.
- Feature Experiment can test a new template picker with
Project Createdas the success metric, and theexperiment()client is already inside@amplitude/unified. - 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
Reference docs
Amplitude is the leading all-in-one analytics platform for building better products. Product and engineering teams use Amplitude to connect product analytics and web analytics with session replay, heatmaps, experimentation, feature flags, and guides and surveys in one unified workflow, with AI agents working across all of it. Learn how Amplitude is building self-improving products with Wave, helping teams turn product data into PRs.