---
name: anytrack-tracking
description: Use whenever you create or change a form, quiz, sign-up, lead capture, booking, or checkout in this app, and when you add, change, or check AnyTrack conversion tracking - the AnyTrack Tracking Tag, conversion events, Stripe payments, or the AnyTrack Click ID sent to a CRM, a database, or a backend. Every lead and every payment must carry the AnyTrack Click ID. Not for other analytics tools such as Google Analytics, PostHog, or Lovable Analytics.
---

# AnyTrack conversion tracking

AnyTrack ties each conversion in this app (a lead, a booking, a purchase) to the ad click that started the visit. AnyTrack then sends the conversion to the connected ad platforms (Meta, Google Ads, TikTok, Microsoft Ads, ChatGPT Ads). The link between the click and the conversion is the **AnyTrack Click ID**. Your job: install the Tracking Tag, send the right events with the right data, and carry the Click ID to every system that records the lead or the sale.

Most tracking is automatic. Write code only for what the Tracking Tag cannot see. When you are not sure, do not write the code: ask the customer, or search the AnyTrack docs.

Public documentation: https://readme.anytrack.io

## The rule that breaks most setups

**Every lead carries the AnyTrack Click ID to the place that stores it.**

A form, a quiz, a sign-up, or a booking request sends the lead to a CRM, a database table, an email tool, or a webhook (for example Zapier or Make). The server code that creates the lead writes the Click ID on it, in the same request. Later, the CRM sends the conversions of that lead (a qualified lead, a meeting, a deal) to AnyTrack. AnyTrack ties them to the ad click and to the website session through the Click ID.

Without the Click ID, the website session and the CRM conversions stay apart. AnyTrack can only try an email match, and the ad platforms can lose the conversion.

This rule applies to every form in the app: the forms that exist now, and every form, quiz, or sign-up that you add later. Steps 6 to 8 show how. A Stripe checkout follows the same rule through the AnyTrack Stripe prompt (step 9).

## When the customer asks for a new form, quiz, or checkout

Apply this skill also after the first setup, for example when the customer asks "Add a quiz that sends leads to HubSpot":

1. Check that the Tracking Tag is in the page head (step 3). If it is missing, do the full setup from step 1.
2. Ask only the questions that the new form needs: usually the destination of the lead (the CRM, question 2) and the custom event on the final submit (question 9).
3. Make the lead path table again from the code (step 2), with the new row. Propose the events of the new form (step 5), with names for the quiz steps. Show the table, the events, and the list of files, and wait for the customer's yes.
4. Build the form as the customer asks, with the tracking of steps 6 and 7: the email as `refId`, `FormSubmit` on the final submit, and the class `at-do-not-track` on each `<form>` element of the form or quiz.
5. Carry the Click ID on the new lead path to its destination (step 8). The row is "Complete" only when the server writes the Click ID in the request that creates the lead.
6. For a new Stripe checkout, apply the AnyTrack Stripe prompt (step 9).

## How to work

1. **Ask first, then build.** Do the interview in step 1 before you change code. Ask only what you cannot read from the project.
2. **Show the plan before you write code.** Show the event plan (step 5) and the list of files you will change. Wait for the customer's yes.
3. **Search the AnyTrack docs for each integration.** Search before you write code for a CRM, a form tool, a booking tool, a payment tool, or an ad platform. In this skill, "search the AnyTrack docs" means:
   - If the AnyTrack Docs MCP is connected (you have a `search_docs` tool), run `search_docs`.
   - If it is not connected, read the pages on https://readme.anytrack.io, and recommend the Docs MCP to the customer (see "Connect the AnyTrack Docs MCP").
4. **Never block the app for tracking.** A lead, a booking, or a payment always goes through, also when AnyTrack does not load (ad blocker, slow network). Wait for AnyTrack 2 seconds at most on a lead form, and 5 seconds at most when a checkout starts. Then continue.
5. **Change only the tracking.** Keep the app's flows, design, routes, and payment logic as they are. Do not remove another tag or pixel without the customer's yes.

## Connect the AnyTrack Docs MCP

This skill covers the app. The AnyTrack Docs MCP holds the setup guides and tracking methods for every integration: CRMs, form tools, booking tools, Stripe, and ad platforms. With it, you answer integration questions from the current AnyTrack docs, not from memory.

Check first: do you have a `search_docs` tool from the AnyTrack Docs MCP? If yes, skip this section. If no, put this recommendation at the top of your interview message (step 1), before the questions. Tell the customer to add the connector, then to continue the chat:

1. Open **Connectors**.
2. Click **+** (or **Add custom**), then select **MCP server**.
3. In **Server name**, enter `AnyTrack Docs`.
4. If Lovable shows the **Connection** list, select **Direct connection**.
5. In **Server URL**, enter `https://docs.anytrack.ai/mcp`.
6. Select **No authentication**, then click **Add server**.

Each member of the workspace adds the server to their own account. The server is used only while you build. It is not part of the published app.

## Step 1. Interview the customer

Ask these questions. Group them in one message. If the AnyTrack Docs MCP is not connected, start the message with the recommendation and its steps (see "Connect the AnyTrack Docs MCP"). Do not wait for the connector: continue with the questions in the same message.

1. **Property ID.** "Paste your AnyTrack Tracking Tag, or your Property ID." The customer copies it in AnyTrack: **Property Settings**, **Tracking Script**. Never invent a Property ID.
2. **CRM.** "Where do your leads go after the form: a CRM (which one?), a spreadsheet, an email, or only this app's database?" Then: "Is this CRM connected in AnyTrack?"
3. **Embedded tools.** "Does the app embed a form, a quiz, or a booking widget from another tool (HubSpot, GoHighLevel, Typeform, Calendly, or other)?"
4. **Payments.** "Do you take payments? With Stripe Payment Links, Stripe Checkout, or another tool? Is the Stripe integration connected in AnyTrack?" For a Stripe flow other than Payment Links, you apply the AnyTrack Stripe prompt (step 9).
5. **Ad platforms.** "Which ad platforms are connected in AnyTrack? Which AnyTrack plan do you use?"
6. **Currency.** "Which currency do you sell in?"
7. **Other domains.** "Does the visitor go to another domain during the funnel (a checkout, a booking page, a member area)?"
8. **Cookie banner.** "Does the app show a cookie consent banner?"
9. **Final form.** "On the final form submit, I send the `FormSubmit` event. Do you also want a custom event there, for example `ApplicationSubmitted`?"

## Step 2. Read the project

Read the code before you change it. Do not assume names. Make this list and show it to the customer:

- The app type: an older React + Vite app (an `index.html` file, server code in edge functions), or a TanStack Start app (the page head is set in the root route, server code runs as server functions and API routes).
- Every route and page, and the router type. A hash router has routes after a `#` sign, for example `/#/pricing`.
- Every form, quiz step, sign-up, and application. Mark each step that collects an email.
- Every checkout entry point: buttons that open Stripe, Stripe Payment Links (`buy.stripe.com`), embedded checkout.
- Every server function or edge function that creates a lead, writes a lead table, or calls a CRM.
- The tracking that is already in the app: the AnyTrack Tracking Tag, Meta Pixel (`fbq`), Google Tag (`gtag`), TikTok Pixel (`ttq`), Microsoft UET Tag (`uetq`), Google Tag Manager, Stape, and any other analytics script.
- The cookie banner, if there is one.

Then make the **lead path table**: one row for each form, quiz, sign-up, or booking request that sends a lead out of the browser. Show it to the customer.

| Form or quiz | Request from the browser | Server function | Destination | Click ID field | Status |
|---|---|---|---|---|---|
| Quiz on `/quiz` | `create-lead` function call | `create-lead` | HubSpot contact | `atclid` | Missing |
| Contact form | `contact` function call | `contact` | `leads` table and HubSpot contact | `atclid` | Complete |

A lead path is complete only when the Click ID goes from the browser (`getClickId()`, step 6) to the server request (field `atclid`) to the field of the destination (step 8). Each row with the status "Missing" is a required fix in your plan. If the browser sends the lead straight to a webhook (for example a Zapier URL), add the Click ID to that request as `click_id`.

## Step 3. Install the Tracking Tag

1. Make sure the app loads the Tracking Tag one time. If it is already in the head, do not add it again.
2. Add the Tracking Tag high in the page head, on every page:
   - React + Vite app: in the `<head>` of `index.html`.
   - TanStack Start app: in the root route head, as an inline script, so every page renders it.
3. Use the customer's tag as they pasted it. If they gave only the Property ID, use this snippet and replace `PROPERTY_ID`:

```html
<script>
  !function(e,t,n,s,a){(a=t.createElement(n)).async=!0,a.src="https://assets.anytrack.io/PROPERTY_ID.js",(t=t.getElementsByTagName(n)[0]).parentNode.insertBefore(a,t),e[s]=e[s]||function(){(e[s].q=e[s].q||[]).push(arguments)}}(window,document,"script","AnyTrack");
</script>
```

4. Add this type declaration as `src/types/anytrack.d.ts`. It tells TypeScript that `AnyTrack` exists, so no later change removes the calls:

```ts
// Type declarations for the AnyTrack global function (loaded by the Tracking Tag).
declare function AnyTrack(command: 'PageView'): void;
declare function AnyTrack(command: 'trigger', eventName: string, attributes?: Record<string, unknown>): string | undefined;
declare function AnyTrack(command: 'atclid'): string | undefined;
declare function AnyTrack(callback: () => void): void;

interface Window {
  AnyTrack: typeof AnyTrack;
}
```

5. AnyTrack runs only in the browser. Call it only in event handlers and in `useEffect`. Never call it during render or in server code.

## Step 4. Do not code what the Tracking Tag does automatically

The Tracking Tag does these things on its own. Never write code for them:

- **`PageView`** on load and on each route change. The Tracking Tag checks the URL about once per second and does not remove duplicates. Router code that calls `AnyTrack('PageView')` records a second `PageView`. The one exception: a hash router. Then call `AnyTrack('PageView')` on each route change.
- **`OutboundClick`** on links to the platforms that AnyTrack knows, such as affiliate links.
- **The Click ID in Stripe Payment Links.** The Tracking Tag adds the Click ID to the `client_reference_id` of each `buy.stripe.com` link. Do not set your own `client_reference_id` on those links.
- **The Click ID in embedded Typeform and Calendly forms**, and the events of forms and checkouts from platforms in the AnyTrack Integration Catalog (for example HubSpot and GoHighLevel forms).
- **The ad-platform pixels.** The Tracking Tag loads the pixels of the ad platforms connected in AnyTrack.
- **UTM parameters and click identifiers** such as `gclid` and `fbclid`.

If the app embeds a form or a booking widget from a platform in the AnyTrack Integration Catalog, add no `trigger` for it: a manual call counts the event a second time. Search the AnyTrack docs for that platform's setup.

## Step 5. Make the event plan

List the moments that matter in this funnel, then propose one event for each. Use a standard event when one fits: AnyTrack maps standard events to each ad platform. A custom event needs a manual mapping in each ad platform.

Standard events (names are case sensitive): `PageView`, `ViewContent`, `Search`, `OutboundClick`, `AddToCart`, `InitiateCheckout`, `AddPaymentInfo`, `FormSubmit`, `Lead`, `CompleteRegistration`, `Schedule`, `Purchase`, `Upsell`.

Typical plan for a lead-generation or service app:

| Moment in the funnel | Event | Where | Attributes |
|---|---|---|---|
| A page or route loads | `PageView` | Automatic | None. Write no code. |
| A visitor views an offer, a service, or a product | `ViewContent` | Browser | `value`, `currency`, `brand` (offer name), `items` |
| A visitor clicks the main call to action (for example "Take the quiz") | Custom, for example `QuizStart` | Browser | `label` |
| Each quiz or form step | Custom, one per step, for example `QuizStep - Personal details` | Browser | the answers of the step that are useful for reporting |
| The step that collects the email | The step event, with `refId` | Browser | `refId`, `email`, the customer attributes (step 6) |
| The final form submit | `FormSubmit`, plus the custom event the customer asked for | Browser | `refId`, the customer attributes (step 7) |
| A booking | `Schedule` | Browser, or the booking tool's integration | `value`, `currency`, `brand` |
| A visitor clicks "Book now", "Join", or "Buy" and the checkout opens | `InitiateCheckout` | Browser | `value`, `currency`, `brand`, `items` |
| The visitor leaves the checkout without a payment (step 9) | Custom `CheckoutAbandoned` | Browser | `value`, `currency`, `brand` |
| The checkout fails to start, or the card form fails | Custom `CheckoutError` | Browser | `brand`, `label` (short error type, no personal data) |
| The payment succeeds | `Purchase` | Server: the AnyTrack Stripe integration | Write no browser code (step 9) |
| Optional: a visitor reads 75% of an offer page | Custom, for example `Scroll75` | Browser | `brand` |
| Optional: a visitor stays 30 seconds on an offer page | Custom, for example `Dwell30s` | Browser | `brand` |

Rules for the plan:

- `items` is an array of `{ id, name, price, quantity }`. `price` and `quantity` are numbers.
- Put a quiz answer in `label`, for example `{ label: 'Lose weight' }`. Never put personal data in `label`.
- The last step of a form is the final submit. Send `FormSubmit` (and the custom event) there, not a step event.
- Send each step event, `Scroll75`, and `Dwell30s` one time for each funnel attempt. Use `trackOnce()` from the helper (step 6) with a key that starts with the funnel name, for example `quiz:step-2`. When the visitor starts the funnel again (a restart button, or a new quiz after the final submit), call `resetOnce('quiz:')`. For `Scroll75` and `Dwell30s`, use a key per page, for example `offer:scroll75`, and call `resetOnce('offer:')` when the page mounts.
- In development, React StrictMode runs each effect two times. The preview can show an event two times. The published app sends it one time. Do not add code for StrictMode.

Then ask the customer:

- "Do you want other names for these events?" Suggest a clear name for each quiz step, for example `QuizStep - Personal details`, so each step can be used as an event in reports and ad platforms.
- "Which of these events do you want in your ad platforms?" Tell them: map each custom event in AnyTrack **Event Mapping** before an ad platform can use it. Do not map `CheckoutError` or `CheckoutAbandoned` to an ad-platform conversion: they are for diagnosis and retargeting audiences.

Event name rules: at most 40 characters. Use letters, numbers, spaces, and `- _ ( ) . : =`. The Tracking Tag removes other characters. Keep the same name for the same moment in every page.

Never send an event from the browser and from the server for the same moment. Pick one path for each event.

## Step 6. Identify the visitor at the first email

Send the email as `refId` the first time the visitor gives it, also in the middle of a quiz. `refId` links the email to the visitor's Click ID. A later conversion that carries only the email (from a CRM, a booking tool, or a payment) can then match the ad click.

Rules:

- Normalize the email one time: trim it and make it lowercase. Use this same value everywhere: as `refId`, as `email`, and in the CRM or backend request.
- Send the email with the event of the step that collects it. If no event fits that moment, send `AnyTrack('trigger', 'Alias', { refId: email })`.
- Keep the customer attributes in `sessionStorage` for the visit, and add them to every later event.
- Send raw values. Never hash an email or a phone number: AnyTrack hashes them for each ad platform. A pre-hashed value can fail to match.
- Attribute names are case sensitive. Use exactly: `email`, `phone`, `firstName`, `lastName`, `fullName`, `city`, `state`, `zipcode`, `country`, `birthdate`. Send `phone` with the country code, for example `+16505554444`, when the form gives the country code or the country. Never guess the country: if you do not know it, send the phone as the visitor typed it. Send `country` as a 2-letter code.

Add this helper as `src/lib/anytrack.ts` and use it for every event:

```ts
// AnyTrack helper: sends events with the customer attributes of the visit,
// and reads the AnyTrack Click ID for the backend, the CRM, and Stripe.
type Attributes = Record<string, unknown>;

const TRAITS_KEY = 'anytrack_traits';
const CLICK_ID_KEY = 'anytrack_click_id';
const TRAIT_NAMES = ['email', 'phone', 'firstName', 'lastName', 'fullName', 'city', 'state', 'zipcode', 'country', 'birthdate'];

export function normalizeEmail(email: string): string {
  return email.trim().toLowerCase();
}

// In-memory copy, so the attributes stay available when sessionStorage is blocked.
let memoryTraits: Attributes = {};

function readTraits(): Attributes {
  try { return { ...JSON.parse(sessionStorage.getItem(TRAITS_KEY) || '{}'), ...memoryTraits }; } catch { return { ...memoryTraits }; }
}

// Save the customer attributes for the rest of the visit.
export function rememberTraits(traits: Attributes): Attributes {
  const clean: Attributes = {};
  for (const name of TRAIT_NAMES) {
    const value = traits[name];
    if (typeof value === 'string' && value.trim()) clean[name] = name === 'email' ? normalizeEmail(value) : value.trim();
  }
  const all = { ...readTraits(), ...clean };
  memoryTraits = all;
  try { sessionStorage.setItem(TRAITS_KEY, JSON.stringify(all)); } catch { /* storage blocked */ }
  return all;
}

function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); }

// Send one event. It never throws and never waits: AnyTrack queues the event
// until the Tracking Tag is ready.
export function track(eventName: string, attributes: Attributes = {}): void {
  if (typeof window === 'undefined' || typeof window.AnyTrack !== 'function') return;
  const traits = readTraits();
  const payload: Attributes = { ...traits, ...attributes };
  if (typeof traits.email === 'string' && payload.refId === undefined) payload.refId = traits.email;
  try {
    window.AnyTrack(() => {
      try { window.AnyTrack('trigger', eventName, payload); } catch { /* invalid event, ignore */ }
    });
  } catch { /* AnyTrack not available */ }
}

// Send an event one time for each funnel attempt, for example a quiz step.
// The Back and Next buttons do not send it again. A page reload starts a new
// attempt. Call resetOnce('<prefix>') when the visitor starts the funnel again.
const sentOnce = new Set<string>();

export function trackOnce(key: string, eventName: string, attributes: Attributes = {}): void {
  if (sentOnce.has(key)) return;
  sentOnce.add(key);
  track(eventName, attributes);
}

export function resetOnce(prefix = ''): void {
  for (const key of [...sentOnce]) if (key.startsWith(prefix)) sentOnce.delete(key);
}

// The AnyTrack Click ID of the visit, for a backend, a CRM, or Stripe.
// Tries every 300 ms. Resolves '' when AnyTrack does not answer in time.
// Do not use the return value of a 'trigger' call: with refId, it returns the refId.
export async function getClickId(waitMs = 2000): Promise<string> {
  const deadline = Date.now() + waitMs;
  while (Date.now() < deadline) {
    try {
      const value = typeof window.AnyTrack === 'function' ? window.AnyTrack('atclid') : '';
      if (typeof value === 'string' && value.length > 0) {
        try { sessionStorage.setItem(CLICK_ID_KEY, value); } catch { /* storage blocked */ }
        return value;
      }
    } catch { /* not ready yet */ }
    await sleep(300);
  }
  try { return sessionStorage.getItem(CLICK_ID_KEY) || ''; } catch { return ''; }
}
```

Example, a quiz step that collects the email:

```ts
const traits = rememberTraits({ email, firstName, lastName, phone });
trackOnce('quiz:step-2', 'QuizStep - Personal details', { refId: traits.email, brand: 'Coaching quiz' });
```

AnyTrack matches `refId` exactly, and it keeps the case. That is why the email is lowercase everywhere.

## Step 7. Track the final form submit

On the final submit of each lead form, send `FormSubmit` by default. If the customer asked for a custom event too, send it after `FormSubmit`, with the same attributes.

1. In the submit handler, save the form's customer attributes with `rememberTraits(...)`, then send the event: `track('FormSubmit', { brand: '<form or offer name>' });`. The helper adds `refId` and the customer attributes.
2. Read the Click ID: `const clickId = await getClickId();`. Add it to the request that saves the lead (step 8). If it is empty, send the lead without it.
3. Send the event one time for each submit. Do not send it again on a re-render, on a retry, or on a later step with the same email.
4. Add the class `at-do-not-track` to the `<form>` element (to each `<form>` element of a quiz with more than one), and add no `--CLICK-ID--` hidden field. The Tracking Tag can send an automatic `FormSubmit` for a form with that placeholder, and for any POST form when **Catch-all Events**, **Form Submit** is on in the property settings. The class stops every automatic event of the form, so the event of item 1 counts one time. It does not stop `track()`. The Click ID comes from `getClickId()`, so the form needs no placeholder.
5. Never stop or delay the submit for more than 2 seconds because of tracking.

If the form is not built in this app (a HubSpot, GoHighLevel, or Typeform embed), do not send `FormSubmit`: the platform's integration sends the event.

Some AnyTrack docs pages give a different method for a custom form: a hidden `--CLICK-ID--` field, and the automatic `FormSubmit` (for example the "Custom Forms" prompt of the HubSpot form tracking page). In this app, use the method of this step instead: it adds `refId` and the customer attributes to the event. From those pages, take only the CRM field for the Click ID. Never use both methods in one form.

## Step 8. Carry the Click ID to the backend and the CRM

Send the Click ID with every lead: it gives the most exact match. Without it, some integrations try to match the lead by its email, which step 6 links to the visitor as `refId`. If no identifier matches, the conversion shows as "Unknown" in AnyTrack. So:

1. If the app stores leads, orders, or bookings in a table, add a nullable text column `atclid` to that table. Save the Click ID in the same row as the lead.
2. Send the Click ID in every request from the browser to the server that creates a lead, as the field `atclid`.
3. In the server code that creates the CRM contact, write the Click ID to the CRM field that AnyTrack reads, in the same request that creates the contact:

| CRM | Field for the Click ID |
|---|---|
| HubSpot, connected in AnyTrack | The contact property **AnyTrack Click ID**, internal name `atclid`. The AnyTrack app creates it. Do not create it. |
| GoHighLevel, connected in AnyTrack | The custom field `_atid`, field key `contact.atclid`. The AnyTrack app creates it. Do not create it. Get the field ID from the custom fields endpoint, then add it to the `customFields` of the create request. |
| Another CRM connected in AnyTrack | Search the AnyTrack docs for that CRM's Click ID field. If you find none, ask the customer. |
| A CRM that is not connected in AnyTrack, or no CRM | A custom field named `click_id`. Ask the customer to create it in the CRM if the CRM needs that first. |

4. If the Click ID is empty, create the contact without the field: do not send an empty string. If the CRM rejects the field (an error response that names the field), log the error and create the contact again without the field. Never fail the contact creation because of the field. In your report, tell the customer that the CRM rejected the field and what to fix.
5. If the CRM says that the contact already exists, do not fail the lead. Write the Click ID on the existing contact when its Click ID field is empty. Ask the customer before you replace a Click ID that the contact already has.
6. Never generate or replace a Click ID. A UUID, the email, `gclid`, or `fbclid` is not a Click ID.
7. Keep API keys and tokens in the project secrets. Never put a CRM token in browser code.

When the CRM is connected in AnyTrack, the CRM integration also records the lead. For example, the HubSpot integration tracks each new contact (**Contact created**) as `Lead` by default. One submit then gives `FormSubmit` from the browser and `Lead` from the CRM. Tell the customer to pick one of the two as the lead conversion in each ad platform (in AnyTrack **Event Mapping**), not both.

## Step 9. Checkout and Stripe: apply the AnyTrack Stripe prompt

- **Stripe Payment Links (`buy.stripe.com`):** change nothing. The Tracking Tag adds the Click ID.
- **Every other Stripe flow** (Checkout Session, embedded checkout, Payment Element, PaymentIntent, Subscription): apply the AnyTrack Stripe prompt in the appendix of this skill. Follow it exactly, as its own change. For checkout code, the prompt wins over every other rule in this skill.

How the prompt fits with this skill:

- **Tag check.** Start the prompt only after step 3 is done. The customer's yes to the plan with the Tracking Tag counts as the confirmation that the prompt asks for, and the tag in the source code of the page head counts as installed. Read the page head again before you start. If the customer said no to the Tracking Tag, stop as the prompt says.
- **No publish.** You never publish or deploy. The customer publishes after the review, then runs the checks of step 12.
- **Helper.** In checkout code, use only the prompt's helper `getAnyTrackClickId` (it waits up to 5 seconds). Never call `getClickId()` in checkout code. If the app has no lead form, do not add `getClickId()`.
- **Report.** End the Stripe change with the report of the prompt and "✔️Finished successfully".
- **Checkout events, second change.** The prompt adds no events. After the report, propose the checkout events of your event plan as a second change. Make it after the customer's yes, and end it with a short list of the changed files.
  - `InitiateCheckout`: one time for each checkout attempt, when the visitor clicks the checkout button, before the Click ID wait. The Click ID wait and the server call give the Tracking Tag time to send the event before the redirect. Never call `track()` and change `window.location` in the same moment.
  - `CheckoutAbandoned` when the visitor leaves the checkout without a payment. Embedded checkout (inside the app): when the visitor closes the checkout without a payment. Hosted checkout (a redirect to a Stripe page): when the visitor comes back through the `cancel_url`. If the `cancel_url` has no marker that shows the return, add a query parameter such as `?checkout=cancelled` to it in this second change, never in the Stripe change. If the code does not show which type the app uses, ask the customer.
  - `CheckoutError` when the checkout fails to start or the card form shows an error.
- `Purchase` comes from the AnyTrack Stripe integration, on the server. Do not send `Purchase` from the browser: that counts each sale two times. Tell the customer to connect the Stripe integration in AnyTrack if it is not connected.

## Step 10. Server-side events

Use the browser for every event that happens in the browser. Send an event from the server only when the browser does not see it, for example a lead status that changes in a back-office page, or a payment from a tool without an AnyTrack integration.

1. The customer creates a **Custom Integration** in the AnyTrack Integration Catalog and copies its URL. It has this form: `https://t1.anytrack.io/<account-id>/collect/<integration-name>`. Never build the URL yourself.
2. Ask the customer for the URL as a project secret, named `ANYTRACK_WEBHOOK_URL`. Do not use a `VITE_` name: the URL must stay on the server.
3. In the server code, send a POST with a JSON body:

```json
{
  "event_name": "Lead",
  "click_id": "<the atclid saved with the lead>",
  "ref_id": "<the lowercase email>",
  "transaction_id": "<a unique ID for this event, for example lead-123-qualified>",
  "value": 0,
  "currency": "USD",
  "email": "jane@example.com",
  "first_name": "Jane",
  "last_name": "Doe"
}
```

4. Send `click_id` when you have it, and always send `ref_id` with the normalized email. Name the field `click_id`, not `atclid` or `_atid`. Send `event_name` and a `transaction_id` on each event.
5. A `200` response means AnyTrack received the request, not that the conversion was attributed. Log the status, and check the result in the integration's **Events Log** tab.

## Step 11. Prevent duplicate data

The Tracking Tag loads the pixels of the ad platforms connected in AnyTrack. A second copy of a pixel sends the same events again, and the ad platform counts them two times.

1. List every pixel, `gtag`/`fbq`/`ttq`/`uetq` snippet, and tag manager container (Google Tag Manager, Stape) in the app.
2. Show the list to the customer. Mark the ones that send events to an ad platform that is connected in AnyTrack.
3. For each ad platform that is connected in AnyTrack, ask the customer to check the pixel's **Settings** tab in AnyTrack **Tracking Pixels**:
   - **Enable Tracking** on, and (Meta only) **Enable Server Only Tracking** off: the Tracking Tag loads that pixel in the browser. Tell the customer to remove the old pixel code and the tag-manager tags of that ad platform when the AnyTrack setup goes live. The old copies send duplicate events.
   - **Enable Tracking** off, or **Enable Server Only Tracking** on: the Tracking Tag does not load that pixel in the browser. Do not recommend a removal. Tell the customer what the old pixel does, and let them decide.
4. Keep the pixels and tags of ad platforms that are not connected in AnyTrack, and the analytics scripts.
5. Remove a pixel only after the customer says yes.
6. After the change, check the events in each ad platform's test events tool (step 12).

Other settings that are done in the AnyTrack dashboard, not in code:

- **Other domains:** if the funnel goes to another domain, the customer sets it up in AnyTrack **Property Settings**, **Cross-Domain Settings**. Search the AnyTrack docs for "cross-domain".
- **Cookie banner:** Consent Mode needs a setup that depends on the banner. Search the AnyTrack docs for "Consent Mode". Do not write `setConsent` code without that page.

## Step 12. Verify the setup

Give the customer these checks at the end. You do not publish the app. The customer publishes it, then tests on the live URL.

1. Install the AnyTrack Pixel Helper extension in Chrome and open the app. It shows the Property ID.
2. Open the app with a test parameter, for example `?utm_source=test`. Go to 3 routes. The AnyTrack **Conversions Report** shows one `PageView` for each route, not two.
3. Go through the funnel with a new email. The Conversions Report shows each event of the event plan, one time each, with the customer attributes.
4. For each row of the lead path table: submit the form with a new email, then open the lead in its destination (the CRM, the table, the webhook tool). The Click ID field holds a value that starts with the Property ID. If the app also saves the lead in its database, the `atclid` column holds the same value.
5. Make a test payment in Stripe test mode. The Stripe payment shows `atclid` in its metadata (or the Payment Link payment shows `client_reference_id`).
6. For a server-side event, open the Custom Integration's **Events Log** tab. The event shows a match.
7. In each ad platform, open the test events tool (for example Meta **Events Manager**, **Test events**) and confirm that the events arrive.

## Never

- Never send `PageView` from router code (except for a hash router).
- Never use `AnyTrack('track', ...)`. There is no `track` command: it is Meta Pixel syntax, and AnyTrack shows an "Unknown command" error. Use `AnyTrack('trigger', ...)`.
- Never install a second Tracking Tag, or one tag per page component.
- Never invent a Property ID or a Click ID.
- Never ship a form, quiz, or sign-up whose lead reaches a CRM, a table, or a webhook without the Click ID.
- Never write Stripe checkout code without the AnyTrack Stripe prompt (step 9).
- Never send the same event from the browser and from the server.
- Never send `Purchase` from the browser when the AnyTrack Stripe integration records the payment.
- Never hash customer data, and never change the case of attribute names.
- Never send `value` as text. It is a number without a currency sign: `49.9`, not `"$49.90"`.
- Never put tokens, API keys, or the Custom Integration URL in browser code.
- Never remove another tag, pixel, or tag manager without the customer's yes.

## Appendix: AnyTrack Stripe prompt

Apply this prompt in step 9. It is the same prompt as on the AnyTrack Stripe page of the docs.

````text
# AnyTrack: Pass the AnyTrack Click ID to Stripe

We at AnyTrack provide this prompt to help you pass the **AnyTrack Click ID** (`atclid`) into Stripe. Inspect this website and implement the required changes using its existing framework, backend, Stripe integration, and purchase types. Cover every active checkout path you find, while retaining correct existing attribution code. Use the name “AnyTrack Click ID” throughout your implementation notes and customer-facing explanations.

**Strict scope: do not change the architecture or modify any existing flow. The final result must behave exactly as it does today, with the only functional addition being retrieval of the AnyTrack Click ID generated by our Tracking Tag and passing it to Stripe through the existing integration. Additional changes or fixes are out of scope.**

Make only the minimal attribution-specific changes needed in existing code paths and payloads. The only permitted timing change is awaiting the bounded async `atclid` lookup described below before the existing checkout creation request. Do not refactor, redesign, migrate integrations, upgrade dependencies, add checkout steps, or otherwise change UI, business logic, payment behavior, request sequencing, or payment retry behavior. Do not fix unrelated issues you discover. If attribution cannot be added within these constraints, report the specific limitation instead of changing the architecture or flow. Do not deploy or publish the changes to the live site: the customer reviews and tests them first. These constraints apply to every instruction below.

The customer may use a Stripe server SDK or make direct HTTP requests to the Stripe API. Both approaches are supported. Keep whichever approach the customer already uses; do not replace SDK calls with direct API requests or introduce an SDK where direct requests already work. The intended flow in either case is:

`Async AnyTrack('atclid') lookup in the browser → existing checkout/payment request's atclid field → backend → Stripe metadata.atclid (value unchanged)`

Implement when code access is available; otherwise provide concrete instructions for the detected integration. Ask only for information you cannot establish from the project and that is necessary to proceed.

## 1. Discover the integration before editing

First, verify that the customer's AnyTrack Tracking Tag is installed on the relevant website pages. **If the tag is missing, stop the task and tell the customer: “The AnyTrack Tracking Tag is not installed. Please install it on your website and confirm when it is installed so I can continue.” Do not continue implementation until the customer explicitly confirms installation.** After confirmation, re-check the installation before proceeding; if it is still missing, report that and remain stopped. Do not install the tag yourself, request a snippet as a substitute for confirmation, copy another site's tag, or invent a property ID.

This is an implementation prerequisite. Once the tag is installed, temporary runtime unavailability is handled by the bounded lookup below; an unavailable `window.AnyTrack` during page loading alone does not establish that the installation is missing.

Trace each checkout entry point to the code or platform that creates the Stripe object. Inspect the frontend, request schemas, backend routes or server actions, Stripe calls, installed SDK versions, configured API version, and any existing attribution mapping. Do not print secret values.

For projects built with Lovable, Base44, or similar platforms, identify the existing checkout implementation and platform-native backend functions or payment integration. Inspect the actual project; do not assume a particular backend or Stripe flow from the platform name. Pass the browser-retrieved AnyTrack Click ID through that existing mechanism and attach it where the Stripe object is created, using the matching metadata fields in section 4. Preserve platform SDK calls, function invocation, authentication, secrets management, and checkout behavior. If a managed integration does not expose the required per-checkout metadata fields, report the specific limitation; do not replace the integration or introduce a new backend.

Identify:

- Whether the backend uses a Stripe server SDK, direct HTTP API requests, or both, and where each Stripe object is created.
- How checkout data reaches the backend: JSON, FormData/multipart, URL-encoded or native form submission, framework server actions, or another existing transport. Identify its parser and validation schema as well.
- Hosted Checkout, embedded Checkout, custom Checkout using the Checkout Sessions API, direct PaymentIntents, or direct Billing Subscriptions.
- One-time purchases, subscriptions, mixed carts, trials, and delayed or off-session charges actually supported by the site. Use Stripe's mode and recurring price configuration as evidence; product names such as “monthly supply” are insufficient.
- Where the AnyTrack Tracking Tag loads, which property it belongs to, and whether existing code already collects and passes the AnyTrack Click ID.
- When Stripe objects are created relative to the checkout action, including objects created on page load or after a queued backend job.

A Payment Element alone does not identify the backend flow. Trace whether its client secret comes from a Checkout Session, a direct PaymentIntent, or a Subscription's invoice payment.

Briefly list the detected flows and evidence, then implement the applicable branches. Keep the existing SDK/API version and UI mode values; this task does not require an integration migration.

## 2. Retrieve the AnyTrack Click ID in the browser

Use the customer's installed AnyTrack Tracking Tag after the prerequisite in section 1 is satisfied. Avoid duplicate AnyTrack Tracking Tag installations.

Don't create new utilities for getting the AnyTrack Click ID, but rely on the below helper `getAnyTrackClickId`. Don't generate it yourself by directly calling `AnyTrack('atclid')` or substitute a random UUID, email, Stripe customer ID, `gclid`, or `fbclid`. Use the helper `getAnyTrackClickId` to get the AnyTrack Click ID.
The helper `getAnyTrackClickId` is an async function, it tries to get the AnyTrack Click ID and retries every 300ms during 5 seconds before giving up. In worst case the helper will return undefined, which is safe to send to the API later.

Call this helper only in the browser checkout handler, using `await getAnyTrackClickId()` where appropriate. When a new checkout/purchase flow attempt begins, the call of `getAnyTrackClickId` function will get the AnyTrack Click ID to include it into the request that eventually sends the value to Stripe (as instructed in the later section).

```js
async function getAnyTrackClickId(browser = globalThis) {
  const deadline = performance.now() + 5000;

  while (performance.now() < deadline) {
    try {
      const AnyTrack = browser?.AnyTrack;
      if (typeof AnyTrack === 'function') {
        const atclid = AnyTrack('atclid');
        if (typeof atclid === 'string' && atclid.length > 0) return atclid;
      }
    } catch {
      // The tracker may become available on a later attempt.
    }

    const remaining = deadline - performance.now();
    if (remaining <= 0) break;
    await new Promise((resolve) => setTimeout(resolve, Math.min(300, remaining)));
  }

  console.error('[AnyTrack] Could not retrieve the AnyTrack Click ID within 5 seconds.');
  return undefined;
}
```

Retain the lookup promise and its result per checkout attempt using the existing browser submission handler or attempt context; do not require a particular frontend framework or state model. Keep the existing idempotency key and access token associated with the attempt, if used. Reuse the same promise/result for the same attempt, including a final `undefined`; a payment/API retry must not restart the 5-second lookup. Preserve the existing busy/submission guard so repeated clicks cannot create parallel checkouts. If an attempt is canceled or replaced while waiting, its result must not submit a stale checkout. Start a new lookup only for a genuinely new attempt. Do not add persistence or a new payment retry system. If the customer already carries checkout context across steps or queued jobs, pass the field through that existing context.

## 3. Carry attribution through the existing backend boundary

Preserve the customer's existing browser-to-backend transport, content type, endpoint or server action, parser, and submission behavior. Do not convert forms or server actions to JSON/fetch, introduce a new API endpoint, or replace the transport to add attribution. Always name the field or argument carrying the AnyTrack Click ID `atclid` throughout the existing checkout context, payloads, schemas, and backend mappings. If an existing attribution field uses another name, update that field and its mappings consistently to `atclid` within the existing transport. The final Stripe metadata key must also be exactly `atclid`.

After awaiting the lookup, pass the resolved string unchanged using the existing format. On timeout, `undefined` is returned. Do not serialize it as an empty string, `null`, or the string `"undefined"`:

| Existing browser-to-backend transport | On successful lookup | On timeout |
| --- | --- | --- |
| JSON | Include `atclid` in the existing payload. | Omit the property; `JSON.stringify` also omits object properties whose value is `undefined`. |
| FormData/multipart or URLSearchParams | Set the `atclid` field to the resolved string using the existing serializer. | Omit/delete the attribution field; do not pass `undefined` to `.set()` or `.append()`, which would stringify it. |
| Native HTML form | Populate a hidden input named `atclid` before the existing submission. | Remove or disable that attribution input so it is not submitted. |
| Framework server action or other transport | Pass `atclid` through the existing action's supported argument or form payload. | Use its supported optional-field representation, without inventing a placeholder value. |

For form submissions, integrate the bounded lookup into the existing submit handling while preserving validation, the submitter's name/value and action, CSRF fields, redirects, and duplicate-submission protection. Ensure serialization round-trips the exact AnyTrack Click ID; transport encoding is not sanitization. Read the field on the server through the existing parser or action argument rather than assuming a JSON body.

Hosted, embedded, and custom Checkout send the field through the customer's existing Checkout Session creation request; direct one-time checkout uses the existing PaymentIntent creation request; direct subscription checkout uses the existing Subscription creation request. Route names such as `/api/checkout-sessions`, `/api/payment-intents`, and `/api/subscriptions` are examples, not names to impose on the project. In all eight cases the browser sends the AnyTrack Click ID to the application's backend, and the backend sends it to Stripe.

Update every intervening schema, validator, action, service, and queued payload that could drop this field. For delayed creation, retain the browser-captured value with the specific order or checkout context until the backend creates the Stripe object.

On the server, pass the supplied AnyTrack Click ID through unchanged. Check only that it is a non-empty string before adding metadata. Do not sanitize, trim, truncate, remove control characters, hash, or otherwise rewrite it:

```js
function createAtclidMetadata(atclid) {
  return typeof atclid === 'string' && atclid.length > 0 ? { atclid } : {};
}
```

Adapt the same behavior to the backend's language. The value retrieved from AnyTrack must be identical to the value sent in Stripe metadata. Missing attribution must not prevent checkout or send an empty `metadata.atclid` value that could clear an existing value.

Pass the extracted `atclid` field or argument to `createAtclidMetadata` (or its equivalent in the backend's language), then merge the result into the relevant existing metadata maps without replacing other keys or nested payment/subscription settings. Extraction may use a parsed body field such as `body.atclid`, `formData.get('atclid')`, or an `atclid` server-action argument, depending on the existing integration. Attach this metadata during Stripe object creation without a separate attribution update request. If a customer's existing flow pre-creates an object, use an existing server-side update path for the correctly owned object only if it can carry the field without changing the flow. Otherwise report the limitation. Do not move object creation, add requests or checkout steps, or reorder confirmation to accommodate attribution.

Keep secret-key Stripe requests on the backend. Do not add arbitrary metadata to Stripe.js confirmation arguments, billing details, Payment Element options, or a hosted Checkout URL. Use metadata for the AnyTrack Click ID and preserve any existing business use of `client_reference_id`. Preserve server-owned prices, authentication, object ownership, idempotency, capture behavior, subscription settings, and redirect handling.

## 4. Apply the matching Stripe API branch

The table lists fields to supply through the existing Stripe server SDK call or direct HTTP API request. The metadata destinations are the same in both cases; adapt the parameter syntax and serialization to the customer's SDK/language or HTTP client. “Stripe request” in this prompt includes either approach. Implement only the rows the project uses, but cover all discovered entry points for those rows.

| Detected integration | Purchase type | Fields to populate with the unchanged AnyTrack Click ID |
| --- | --- | --- |
| Hosted Checkout Session | One-time | `metadata.atclid` and `payment_intent_data.metadata.atclid` |
| Hosted Checkout Session | Subscription | `metadata.atclid` and `subscription_data.metadata.atclid` |
| Embedded Checkout Session | One-time | `metadata.atclid` and `payment_intent_data.metadata.atclid` |
| Embedded Checkout Session | Subscription | `metadata.atclid` and `subscription_data.metadata.atclid` |
| Custom Checkout using Sessions | One-time | `metadata.atclid` and `payment_intent_data.metadata.atclid` |
| Custom Checkout using Sessions | Subscription | `metadata.atclid` and `subscription_data.metadata.atclid` |
| Direct PaymentIntent, including Elements | One-time | PaymentIntent `metadata.atclid` |
| Direct Billing Subscription, including Elements for its invoice payment | Subscription | Subscription `metadata.atclid` |

For Sessions, branch on the actual `mode`: use `payment_intent_data` for `payment` and `subscription_data` for `subscription`. A mixed cart handled in subscription mode follows the subscription branch. Keep Session metadata as well as the underlying object's metadata. See [Checkout Session creation](https://docs.stripe.com/api/checkout/sessions/create), [PaymentIntent creation](https://docs.stripe.com/api/payment_intents/create), and [Subscription creation](https://docs.stripe.com/api/subscriptions/create).

For subscriptions, attach the AnyTrack Click ID to the Subscription at creation. Renewals do not require a new browser lookup or attribution request. Do not add separate writes of `atclid` to invoice metadata or the subscription's invoice PaymentIntent, invoice updates, renewal hooks, or webhook handlers. If inspecting an existing downstream consumer, distinguish Stripe's own metadata propagation from writes performed by the application; see [Stripe's metadata propagation rules](https://docs.stripe.com/metadata#copy-metadata-to-another-object).

Do not use Customer metadata alone as the transaction attribution source or overwrite historical subscription attribution on every visit. For SetupIntents, setup-mode Sessions, invoice-only flows, subscription schedules, or legacy Charge integrations, trace the eventual payment-producing object and check its version-specific API. Saving a payment method is not a purchase; preserve the AnyTrack Click ID through the application's existing context and attach it when the actual payment or subscription is created.

Don't create a new webhook, or change if any webhooks exist. The current task is only about passing the AnyTrack Click ID to Stripe.

## 5. Verify each detected path and report the result

Use focused automated checks and Stripe test mode or sandbox where available. Never create live charges to verify tracking. Cover:

- The AnyTrack Tracking Tag installation prerequisite is satisfied. If installation is missing, stop and wait for the customer's explicit confirmation before continuing implementation.
- A retrieved string is named `atclid` throughout the existing checkout context and backend boundary and passes unchanged to every required Stripe `metadata.atclid` field.
- The existing browser-to-backend transport and parser are preserved. Verify successful field extraction and omission on timeout using the actual JSON, form, server-action, or other supported payload; no placeholder string is sent.
- Each active UI/purchase combination, including any pre-created objects, deferred creation, trials, or retry paths the site actually supports.
- Lookup attempts run immediately and then every 300 ms until success or the 5-second deadline. Missing or throwing AnyTrack, bootstrap queue return values, and empty results are retried. Replacing the bootstrap function with the loaded SDK during polling works.
- Success resolves the exact AnyTrack Click ID and stops polling. Timeout logs one error without the raw AnyTrack Click ID, resolves `undefined`, and lets checkout proceed with the optional attribution field omitted and no added `atclid` metadata. No timer continues polling after completion.
- A missing AnyTrack Click ID does not erase existing Stripe metadata. Payment/API retries reuse the original attempt's lookup promise/result, including `undefined`, and do not create another polling window. Separate checkout attempts keep their own state.
- Existing submission guards prevent duplicate requests while awaiting the lookup, and canceled or replaced attempts cannot submit after their lookup resolves.
- The architecture and existing flows remain unchanged apart from the explicitly requested bounded lookup before checkout creation. Review the diff to confirm every production-code change is strictly necessary to retrieve or pass `atclid`, with no unrelated changes or fixes.

When test/sandbox credentials and access permit, complete a sandbox checkout and inspect the resulting Stripe objects server-side or in the Dashboard. Distinguish source inspection, mocked requests, actual Stripe object verification, and confirmed AnyTrack ingestion; report only what you verified.

Finish with a compact table of detected flows, changed files or platform settings, destination fields, verification results, and any remaining customer action. If all relevant paths are already correct, verify and report that rather than rewriting them.

The scope is carrying the AnyTrack Click ID into Stripe. Preserve existing analytics events; do not add duplicate `InitiateCheckout`/`Purchase` events or a new webhook pipeline as a side effect. 

After the setup is ready to generate atclid and pass it to Stripe as a metadata field, and the project's flows are covered, with this, tell at the end: ✔️Finished successfully
````
