> ## 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.

# Next.js Integration

> Install the AgentRef tracking script in a Next.js app and keep affiliate attribution working across App Router or Pages Router.

Next.js is one of the cleanest AgentRef integrations because you can install the tracking script once in a shared layout and cover the whole app.

## Before you start

* In AgentRef, set the program website to the same root domain your Next.js app serves.
* Copy the exact script snippet from `Settings -> Integration`.
* If you split traffic between `www.example.com` and `app.example.com`, install the script on both surfaces if either one can receive affiliate traffic or start checkout.

## Recommended installation

<Tabs>
  <Tab title="App Router">
    Use `next/script` in `app/layout.tsx` so the script loads once for the whole application.

    ```tsx theme={null}
    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="Pages Router">
    If you still use the Pages Router, install the script in `_app.tsx` or `_document.tsx`. `_app.tsx` is usually the simplest choice.

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

    export default function App({ Component, pageProps }: AppProps) {
      return (
        <>
          <Script
            src="https://www.agentref.co/api/tracking/script.js?pid=YOUR_PROGRAM_ID"
            strategy="afterInteractive"
          />
          <Component {...pageProps} />
        </>
      );
    }
    ```
  </Tab>
</Tabs>

<Tip>
  Do not append the script from a React effect unless you have a strong reason. In Next.js, `next/script` is the cleanest and least error-prone installation path.
</Tip>

## Checkout compatibility in Next.js

| Checkout pattern                                                                  | Recommendation                                                                                                                                 |
| --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| Stripe Payment Links, Buy Buttons, or Pricing Tables rendered in your app         | Supported directly. Keep the AgentRef script on the same page.                                                                                 |
| Server-created Checkout Sessions in API routes, server actions, or route handlers | Supported, but you must bridge `window.AgentRef.getCheckoutMetadata()` into Stripe metadata. Use the [Stripe guide](/docs/integration/stripe). |
| Checkout starts on a different root domain                                        | First-party cookies will not carry across roots. Move the flow onto one root or build a server-side handoff intentionally.                     |

## Consent, CSP, and multi-domain notes

* If you use a cookie banner, call `window.AgentRef.setConsent('granted')` after the visitor accepts tracking. See [Consent and GDPR](/docs/tracking/consent-gdpr).
* If you use a Content Security Policy, allow `https://www.agentref.co` in `script-src` and `connect-src`.
* If your marketing site and app live on sibling subdomains, install AgentRef on both when both can begin the journey.

## Verify the installation

<Steps>
  <Step title="Run a real affiliate click">
    Open a live test link from AgentRef and land on your Next.js app.
  </Step>

  <Step title="Check browser cookies">
    Confirm that `agentref_cid` and `agentref_pid` exist in DevTools.
  </Step>

  <Step title="Use debug mode">
    Add `?agentref_debug=1` to the URL and inspect the browser console.
  </Step>

  <Step title="Check AgentRef diagnostics">
    Open the tracking health panel or call `/api/v1/programs/:id/tracking/status`.
  </Step>
</Steps>

## Troubleshooting

* `window.AgentRef` is undefined: the script has not loaded yet. Trigger checkout only after the page is interactive.
* Cookies exist on `www` but not in your app subdomain: install the script on both subdomains and make sure the program website points at the shared root.
* Clicks are recorded but conversions are missing: your Next.js checkout path probably creates Stripe sessions server-side and still needs the [Stripe metadata bridge](/docs/integration/stripe).

## Related docs

<CardGroup cols={3}>
  <Card title="Stripe Checkout" icon="credit-card" href="/docs/integration/stripe">
    Custom Checkout Session metadata bridge for Next.js backends.
  </Card>

  <Card title="JavaScript Snippet" icon="code" href="/docs/tracking/javascript-snippet">
    Full cookie, parameter, and API behavior.
  </Card>

  <Card title="Consent and GDPR" icon="shield" href="/docs/tracking/consent-gdpr">
    Gate tracking until the visitor grants consent.
  </Card>
</CardGroup>
