> ## Documentation Index
> Fetch the complete documentation index at: https://agentref.co/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript Snippet

> Install the AgentRef tracking script on your site and configure URL parameters, UTM tracking, sub-IDs, and the DOM API.

The tracking script is a single `<script>` tag that handles click recording, cookie management, and Stripe surface instrumentation automatically. Add it once to your site and it works on every page.

## Installation

<Tabs>
  <Tab title="Plain HTML">
    Add the snippet to your `<head>` on every page, or in a shared layout template:

    ```html theme={null}
    <script
      src="https://www.agentref.co/api/tracking/script.js?pid=YOUR_PROGRAM_ID"
      async
    ></script>
    ```

    Replace `YOUR_PROGRAM_ID` with the UUID from your program's **Tracking** settings page.
  </Tab>

  <Tab title="Next.js">
    Use `next/script` with `strategy="afterInteractive"` so the script loads after hydration without blocking the initial render:

    ```tsx theme={null}
    // app/layout.tsx
    import Script from 'next/script';

    export default function RootLayout({ children }: { children: React.ReactNode }) {
      return (
        <html lang="en">
          <body>
            {children}
            <Script
              src="https://www.agentref.co/api/tracking/script.js?pid=YOUR_PROGRAM_ID"
              strategy="afterInteractive"
            />
          </body>
        </html>
      );
    }
    ```
  </Tab>

  <Tab title="React SPA">
    Load the script once at your app root. The script is safe to add to a `<head>` or `<body>` via any mechanism – it uses `async` internally and does not block rendering:

    ```tsx theme={null}
    // main.tsx / index.tsx
    import { useEffect } from 'react';

    function TrackingScript() {
      useEffect(() => {
        const script = document.createElement('script');
        script.src = 'https://www.agentref.co/api/tracking/script.js?pid=YOUR_PROGRAM_ID';
        script.async = true;
        document.head.appendChild(script);
      }, []);
      return null;
    }

    export default TrackingScript;
    ```
  </Tab>
</Tabs>

<Note>
  The script is served with a 5-minute CDN cache (`Cache-Control: public, max-age=300`). It is safe to load on every page – the script skips tracking if no referral parameter is present and the visitor has no existing attribution cookies.
</Note>

## Script attributes

| Attribute      | Values           | Description                                                    |
| -------------- | ---------------- | -------------------------------------------------------------- |
| `data-debug`   | `"true"`         | Enable debug logging to the browser console on every page load |
| `data-program` | `"<program-id>"` | Override the program ID embedded in the `?pid=` query string   |

```html theme={null}
<!-- Enable debug mode globally -->
<script
  src="https://www.agentref.co/api/tracking/script.js?pid=YOUR_PROGRAM_ID"
  data-debug="true"
  async
></script>
```

You can also trigger debug mode without touching the script tag by adding `?agentref_debug=1` to any URL on your site.

## URL parameters

### Referral parameter (`via`)

Generated AgentRef links use the `via` URL parameter by default:

```
https://yoursite.com?via=abc123
```

Inbound attribution always accepts `via`, `ref`, `r`, and `a`. You can configure additional aliases (for example `aff` or `partner`) in your program's tracking settings. The script checks the default parameters first, then your configured aliases, and uses the first one that has a value.

### UTM parameters

All standard UTM parameters are captured and stored alongside the click record:

| Parameter      | Example                       |
| -------------- | ----------------------------- |
| `utm_source`   | `utm_source=newsletter`       |
| `utm_medium`   | `utm_medium=email`            |
| `utm_campaign` | `utm_campaign=spring_launch`  |
| `utm_term`     | `utm_term=affiliate+software` |
| `utm_content`  | `utm_content=cta_button`      |

### Ad-click IDs

The script captures ad platform click IDs automatically when present:

| Parameter   | Platform            |
| ----------- | ------------------- |
| `gclid`     | Google Ads          |
| `fbclid`    | Meta / Facebook Ads |
| `msclkid`   | Microsoft Ads       |
| `ttclid`    | TikTok Ads          |
| `li_fat_id` | LinkedIn Ads        |

### Sub-IDs

Sub-IDs let affiliates pass custom tracking data through their links for their own attribution needs. Five slots are available:

```
https://yoursite.com?via=abc123&sub1=campaign_a&sub2=email_list&sub3=variant_b
```

Sub-IDs are stored with the click record and appear in conversion data returned to the affiliate via the API.

## Cookies

The script sets the following first-party cookies on your domain:

| Cookie         | Purpose                                            | Duration                          |
| -------------- | -------------------------------------------------- | --------------------------------- |
| `agentref_cid` | Click token – the key for conversion matching      | Program setting (default 30 days) |
| `agentref_src` | Traffic source (e.g., `script_direct`, `redirect`) | Program setting (default 30 days) |
| `agentref_pid` | Program ID                                         | Program setting (default 30 days) |
| `agentref_vid` | Anonymous visitor ID (365-day lifetime)            | 365 days                          |
| `agentref_ts`  | Timestamp of when attribution was set              | Program setting (default 30 days) |

**Cookie characteristics:**

* **First-party only.** Cookies are set on your domain, not `agentref.co`. They are not affected by third-party cookie blocking.
* **Root domain scoping.** Cookies are scoped to `.yoursite.com` so they persist across subdomains (`www`, `app`, `checkout`).
* **`SameSite=Lax`.** Compatible with standard browser security policies. `Secure` flag is added automatically on HTTPS sites.

## DOM API (`window.AgentRef`)

After the script loads, `window.AgentRef` is available with the following methods:

### `AgentRef.ready(callback)`

Run code after tracking has initialized. Use this when you need attribution data at checkout time:

```js theme={null}
window.AgentRef.ready(function() {
  const meta = window.AgentRef.getCheckoutMetadata();
  if (meta.agentref_cid) {
    // Pass to your checkout API
  }
});
```

### `AgentRef.getCheckoutMetadata()`

Returns an object to embed in your Stripe checkout session metadata. Returns `{}` if no active attribution is found.

```js theme={null}
window.AgentRef.getCheckoutMetadata();
// {
//   agentref_cid: "clk_a1b2c3d4e5",
//   agentref_pid: "550e8400-e29b-41d4-a716-446655440000",
//   agentref_source: "script_direct"
// }
```

### `AgentRef.getState()`

Returns the current runtime state of the tracker:

```js theme={null}
window.AgentRef.getState();
// {
//   ready: true,
//   clickToken: "clk_a1b2c3d4e5",
//   programId: "550e8400-...",
//   visitorId: "v_k8m2n4p6...",
//   consentRequired: false,
//   consentGranted: true,
//   source: "script_direct",
//   domainMode: "root"
// }
```

### `AgentRef.refresh()`

Re-run the tracking initialization. Useful after granting cookie consent:

```js theme={null}
AgentRef.setConsent('granted').then(function() {
  // Tracking has been re-initialized with consent
});
```

### `AgentRef.setConsent(status)`

Set the user's consent status. Pass `'granted'` to enable tracking or `'denied'` to clear cookies and disable tracking. See [Consent & GDPR](/tracking/consent-gdpr) for full details.

### `AgentRef.getDebugInfo()`

Returns a diagnostic snapshot. See [Debug Mode](/tracking/debug-mode) for details.
