---
id: "api-reference/integrations/nextjs"
type: "doc"
url: "https://affitor.com/docs/api-reference/integrations/nextjs"
kind: "guide"
updated: "2026-11-08"
---
# Next.js

> Add Affitor tracking to a Next.js (App Router) app: clicks, signups, and sales, with signup steps for Clerk, NextAuth (Auth.js) and Supabase Auth.

This guide wires Affitor into a Next.js App Router app with the three moves every integration needs: **capture the click**, **track the signup**, **track the sale**. Steps 1 and 3 are the same for every app. Step 2 has a tab for each auth setup: **No auth library**, **Clerk**, **NextAuth** (Auth.js) and **Supabase** (Supabase Auth).

:::note

The `@affitor/sdk` package is **Beta**. The documented happy-path works; report issues on GitHub.

:::

## Prerequisites

- Your **program ID** (program menu → **Program settings** → **Business**)
- A **program API key** for server-side calls (leads and sales)
- A Next.js app on the **App Router**
- If you use one, your auth provider configured: **Clerk**, **NextAuth (Auth.js)** or **Supabase Auth**

## 1. Capture the click

Install the SDK and load the tracker once on the client. The tracker reads `?via=` or `?aff=` from the URL and stores a first-party `affitor_click_id` cookie. `AffitorProvider` (from `@affitor/sdk/react`) loads it in the browser; on the server it does nothing and `useAffitor()` returns `null`.

```bash
npm i @affitor/sdk
```

Create a client component that wraps your app in the provider:

```tsx
// app/affitor-provider.tsx
'use client';

import { AffitorProvider } from '@affitor/sdk/react';

export function Providers({ children }: { children: React.ReactNode }) {
  return <AffitorProvider programId="YOUR_PROGRAM_ID">{children}</AffitorProvider>;
}
```

Render it once in your root layout:

```tsx
// app/layout.tsx
import { Providers } from './affitor-provider';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}
```

## 2. Track the signup

Pick the tab for how your app signs users up.

<Tabs items={['No auth library', 'Clerk', 'NextAuth', 'Supabase']}>
<Tab value="No auth library" id="no-auth-library" forceMount>

When a user finishes signing up, link them to their click from your server, with **your own stable user ID**: you'll reuse this exact value at sale time. Send it with the server SDK and your program API key (e.g. in a route handler or right after the DB write):

```ts
// server only, e.g. app/api/signup/route.ts
import { cookies } from 'next/headers';
import Affitor from '@affitor/sdk/server';

const affitor = new Affitor({ apiKey: process.env.AFFITOR_API_KEY! });

// after the user row is created
const clickId = (await cookies()).get('affitor_click_id')?.value;
if (clickId) {
  await affitor.trackLead({
    customerExternalId: user.id, // same ID you'll send at sale time
    clickId,                     // affitor_click_id, forwarded from the cookie
    email: user.email,           // optional
  });
}
```

A lead needs the click: without a `clickId` (or a `customerExternalId` Affitor already knows), the API returns `400` and records nothing, which is expected for visitors who did not come through a partner link.

:::note[Browser `signup()` is provisional by default]

The tracker also has a browser helper, `affitor.signup(user.id, user.email)` (from `useAffitor()` in `@affitor/sdk/react`). Every program requires server-verified leads unless it is set to `browser_allowed`, so a browser-only signup is stored as **provisional**: the API returns `200` with `provisional: true`, but the lead does not settle, does not save your user ID, and does not count or pay per lead until your server sends the lead above or a Stripe Checkout payment for that customer arrives through your connected Stripe account. A sale sent to `/api/v1/track/sale` does not settle it. See [Lead auth policy](/docs/api-reference/track-lead/#lead-auth-policy).

:::

</Tab>
<Tab value="Clerk" id="clerk" forceMount>

The `affitor_click_id` is stored in a **first-party browser cookie**. A server-side Clerk webhook (`user.created`) runs with no access to that cookie, so it cannot supply the click ID on its own.

**Two paths are available. The webhook path (server-side, with your API key) is the one that settles the lead:** every program requires server-verified leads unless it is set to `browser_allowed`, and a lead sent only from the browser stays provisional. See [Lead auth policy](/docs/api-reference/track-lead/#lead-auth-policy).

**Option A: Clerk webhook (`user.created`, recommended)**

Track the signup server-side from Clerk's `user.created` webhook. You **must** forward the click ID yourself. The webhook fires with no browser context, so Affitor cannot attribute the lead without it.

**Step 1.** On the client, read the click ID and store it on the Clerk user before sign-up completes (e.g. in a pre-submit handler or just before redirecting away from your sign-up form):

```tsx
'use client';

import { useSignUp } from '@clerk/nextjs';
import { useAffitor } from '@affitor/sdk/react';

// inside your sign-up form component
const { signUp } = useSignUp();
const affitor = useAffitor(); // null until the tracker has loaded

// during your sign-up form submit
await signUp.update({
  unsafeMetadata: {
    affitor_click_id: affitor?.getClickId() ?? null,
  },
});
```

**Step 2.** In your Clerk webhook handler, read the forwarded click ID and call `trackLead`:

```ts
// app/api/webhooks/clerk/route.ts
import { Webhook } from 'svix';
import Affitor from '@affitor/sdk/server';

const affitor = new Affitor({ apiKey: process.env.AFFITOR_API_KEY! });

export async function POST(req: Request) {
  const payload = await req.text();
  const headers = {
    'svix-id': req.headers.get('svix-id')!,
    'svix-timestamp': req.headers.get('svix-timestamp')!,
    'svix-signature': req.headers.get('svix-signature')!,
  };

  const wh = new Webhook(process.env.CLERK_WEBHOOK_SECRET!);
  const event = wh.verify(payload, headers) as { type: string; data: Record<string, unknown> };

  if (event.type === 'user.created') {
    const user = event.data;
    const unsafeMeta = (user.unsafe_metadata as Record<string, string> | undefined) ?? {};

    await affitor.trackLead({
      customerExternalId: user.id as string,
      clickId: unsafeMeta.affitor_click_id ?? undefined, // forwarded from the browser
      email: (user.email_addresses as Array<{ email_address: string }>)[0]?.email_address,
    });
  }

  return new Response('ok');
}
```

:::note

If `affitor_click_id` is `null` (the user arrived directly, not via an affiliate link), Affitor returns `400` and records nothing, because there is no click to link the lead to. That is expected for non-referred users; `trackLead` resolves with `ok: false` rather than throwing.

:::

**Option B: Client-side `signup()`**

After Clerk completes sign-up, call the tracker's `signup()` from a client component. The tracker reads the `affitor_click_id` cookie automatically; you do not need to pass it explicitly. On programs that require server-verified leads (every program unless it is set to `browser_allowed`), this lead is **provisional**: it does not settle, does not save the user ID, and does not count or pay per lead until the webhook path above sends the lead or a Stripe Checkout payment for that customer arrives through your connected Stripe account. A sale sent to `/api/v1/track/sale` does not settle it. Use it alongside Option A, not instead of it.

Use Clerk's `useUser()` hook to access the signed-in user and `useAffitor()` to access the tracker, then fire `signup()` once both are available:

```tsx
// app/post-signup.tsx: render this on your post-signup or onboarding page
'use client';

import { useEffect } from 'react';
import { useUser } from '@clerk/nextjs';
import { useAffitor } from '@affitor/sdk/react';

export function AffitorSignup() {
  const { user, isLoaded } = useUser();
  const affitor = useAffitor(); // null until the tracker has loaded

  useEffect(() => {
    if (!isLoaded || !user || !affitor) return;
    const email = user.primaryEmailAddress?.emailAddress;
    if (email) affitor.signup(user.id, email);
  }, [isLoaded, user, affitor]);

  return null;
}
```

`user.id` is Clerk's stable `userId`: use this exact value as `customerExternalId` at sale time too.

:::note

Place `<AffitorSignup />` only on the page a new user lands on right after registration (e.g. `/onboarding`, `/welcome`, or wherever your post-signup redirect goes). Rendering it on every page adds nothing: on programs that require server-verified leads, a repeat browser lead returns `200` with `provisional: true` and records nothing new, and on programs set to allow browser leads, a repeat after the lead has settled is rejected with `400`.

:::

</Tab>
<Tab value="NextAuth" id="nextauth" forceMount>

**The cookie gap**

NextAuth's `events.createUser` callback fires **on the server**, once per new user, so it looks like the ideal place to call `trackLead`. It is, but with one important caveat:

**The `affitor_click_id` is a first-party browser cookie.** A server-side callback has no access to it. If you call `@affitor/sdk/server trackLead` from `events.createUser` without a `clickId`, Affitor cannot find the click: the call returns `400` and no lead is recorded.

**Recommended: a server route called after sign-in**

Send the lead from your own route handler, with your program API key. A request from the browser to your route handler carries the first-party `affitor_click_id` cookie, so the server can read it directly.

Stock Auth.js sessions do not include `user.id`. Expose it once in your auth config, and add the type so `session.user.id` compiles:

```ts
// auth.ts
export const { auth, handlers, signIn, signOut } = NextAuth({
  // ...your providers and adapter
  callbacks: {
    session({ session, user, token }) {
      session.user.id = user?.id ?? token.sub ?? '';
      return session;
    },
  },
});

// types/next-auth.d.ts
import type { DefaultSession } from 'next-auth';
declare module 'next-auth' {
  interface Session {
    user: { id: string } & DefaultSession['user'];
  }
}
```

Then the route:

```ts
// app/api/affitor/lead/route.ts
import { cookies } from 'next/headers';
import Affitor from '@affitor/sdk/server';
import { auth } from '@/auth'; // your NextAuth (Auth.js) instance

const affitor = new Affitor({ apiKey: process.env.AFFITOR_API_KEY! });

// Needs the session callback above; without it session.user.id is empty and no lead is sent.
export async function POST() {
  const session = await auth();
  const clickId = (await cookies()).get('affitor_click_id')?.value;
  if (!session?.user?.id || !clickId) return new Response(null, { status: 204 });

  // user.id is the NextAuth user ID; use it as customerExternalId everywhere:
  // signup, sale, Stripe metadata.
  await affitor.trackLead({
    customerExternalId: session.user.id,
    clickId,
    email: session.user.email ?? undefined,
  });
  return new Response(null, { status: 204 });
}
```

Call it once from the browser after NextAuth confirms a new user session:

```tsx
// app/auth-tracker.tsx
'use client';

import { useEffect, useRef } from 'react';
import { useSession } from 'next-auth/react';

export function AffitorAuthTracker() {
  const { status } = useSession();
  const tracked = useRef(false);

  useEffect(() => {
    if (status !== 'authenticated' || tracked.current) return;
    tracked.current = true;
    fetch('/api/affitor/lead', { method: 'POST' });
  }, [status]);

  return null;
}
```

Render it inside your root layout, inside `SessionProvider`:

```tsx
// app/layout.tsx
import { Providers } from './affitor-provider';
import { AffitorAuthTracker } from './auth-tracker';
import { SessionProvider } from 'next-auth/react';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <SessionProvider>
          <Providers>
            <AffitorAuthTracker />
            {children}
          </Providers>
        </SessionProvider>
      </body>
    </html>
  );
}
```

:::note

A lead is recorded once per customer. A repeat call for the same customer (for example on a later sign-in) returns `400` from `trackLead`, which resolves with `ok: false` instead of throwing, so it is safe to ignore.

:::

:::note[Browser `signup()` is provisional by default]

The tracker's browser helper, `affitor.signup(id, email)` from `useAffitor()`, sends the lead without your API key. Every program requires server-verified leads unless it is set to `browser_allowed`, so a browser-only lead is stored as **provisional** and does not settle, save the user ID, or count until your server sends the lead or a Stripe Checkout payment for that customer arrives through your connected Stripe account. A sale sent to `/api/v1/track/sale` does not settle it. See [Lead auth policy](/docs/api-reference/track-lead/#lead-auth-policy).

:::

**Alternative: server-side via events.createUser with click-id forwarding**

If you need the lead recorded the moment the user row is created (before the client redirects), you can use `events.createUser`, but you **must** forward the click ID from the browser yourself.

**Step A.** Read the click ID on the client before the user submits the sign-up form:

```tsx
'use client';
import { useAffitor } from '@affitor/sdk/react';

// In your sign-up form component, read the click ID and include
// it in the request or store it on the user's session/metadata.
const affitor = useAffitor(); // null until the tracker has loaded
const clickId = affitor?.getClickId() ?? null; // the affitor_click_id cookie value
```

**Step B.** Pass it through to your NextAuth config and call `trackLead` in the event:

```ts
// auth.ts (NextAuth config)
import Affitor from '@affitor/sdk/server';
import type { NextAuthConfig } from 'next-auth';

const affitor = new Affitor({ apiKey: process.env.AFFITOR_API_KEY! });

export const authConfig: NextAuthConfig = {
  // ...providers, callbacks, etc.
  events: {
    async createUser({ user }) {
      // user.id is the NextAuth-generated user ID; use it as
      // customerExternalId everywhere: signup, sale, Stripe metadata.
      await affitor.trackLead({
        customerExternalId: user.id,
        clickId: user.affitorClickId ?? undefined, // forwarded from the browser
        email: user.email ?? undefined,
      });
    },
  },
};
```

:::note

`user.affitorClickId` is illustrative: the forwarding mechanism depends on your auth flow. Common approaches: store the click ID in the sign-up form's hidden field and write it to a custom user attribute before `createUser` fires, or pass it through a custom `session` object. Without it, `clickId` is undefined and the lead call returns `400` with nothing recorded.

:::

If you cannot reliably forward the click ID into `events.createUser`, **use the server route above.**

</Tab>
<Tab value="Supabase" id="supabase" forceMount>

Send the lead from your server with your program API key, which is what settles it: every program requires server-verified leads unless it is set to `browser_allowed` (see [Lead auth policy](/docs/api-reference/track-lead/#lead-auth-policy)).

The `affitor_click_id` is a first-party browser cookie. A Supabase Edge Function or DB trigger runs with no access to that cookie, so you must forward the click ID yourself.

**Recommended: Edge Function with a forwarded click ID**

1. On the client, read the click ID and store it on the user's metadata during sign-up:

```tsx
'use client';

import { useAffitor } from '@affitor/sdk/react';

// inside your sign-up form component
const affitor = useAffitor(); // null until the tracker has loaded

// during your sign-up form submit (disable the button until `affitor` is set)
const clickId = affitor?.getClickId() ?? null; // the affitor_click_id cookie value

await supabase.auth.signUp({
  email,
  password,
  options: {
    data: { affitor_click_id: clickId },
  },
});
```

2. In your Edge Function (for example, one you call after sign-up, or one fired by a database webhook on new users), read the forwarded click ID and call `@affitor/sdk/server`:

```ts
// supabase/functions/on-signup/index.ts
import Affitor from 'npm:@affitor/sdk/server';

const affitor = new Affitor({ apiKey: Deno.env.get('AFFITOR_API_KEY')! });

// `user` is the new Supabase user, from your request or webhook payload
const clickId = user.user_metadata?.affitor_click_id;

if (clickId) {
  await affitor.trackLead({
    customerExternalId: user.id,  // Supabase user.id
    clickId,
    email: user.email,
  });
}
```

`user.id` is the stable Supabase UUID. Use this exact value as `customerExternalId` everywhere: at sale time and in any Stripe metadata.

Without a forwarded `clickId`, Affitor cannot find the click: the lead call returns `400` and nothing is recorded. That is expected for users who did not arrive through a partner link.

**Browser `signup()` (provisional by default)**

The tracker also has a browser helper, `affitor.signup(userId, email)`, which you can call from Supabase's client-side `onAuthStateChange` listener. It reads the cookie automatically, but it sends the lead without your API key. On programs that require server-verified leads (every program unless it is set to `browser_allowed`), that lead is stored as **provisional**: it does not settle, does not save the user ID, and does not count or pay per lead until your server sends the lead or a Stripe Checkout payment for that customer arrives through your connected Stripe account. A sale sent to `/api/v1/track/sale` does not settle it. Use it alongside the Edge Function path, not instead of it.

</Tab>
</Tabs>

## 3. Track the sale

Pick one of two paths. This is the real choice: **does Stripe tell us, or does your server?**

Send the same user ID you sent at signup. With an auth provider:

- **Clerk:** use `user.id` (the Clerk user ID) as `affitor_customer_key` in Stripe metadata and as `customerExternalId` in `trackSale`.
- **NextAuth:** use `session.user.id` as `affitor_customer_key` (Stripe path) or `customerExternalId` (server SDK path). It must match the value you sent at signup.
- **Supabase:** use `session.user.id` (your `customerExternalId`) as `affitor_customer_key` in Stripe metadata, or as `customerExternalId` in `affitor.trackSale()`.

### Option A: Stripe integration (recommended for Stripe Checkout)

Connect your Stripe account under **Program settings** › **Payments**, then attach Affitor metadata when you create the Checkout Session in **your own** Stripe account. Affitor receives the account's events through Stripe Connect (you add no webhook) and attributes the sale automatically, with no extra call.

```ts
// server: creating the Checkout Session
const session = await stripe.checkout.sessions.create({
  mode: 'subscription', // or 'payment'
  line_items: [{ price: 'price_xxx', quantity: 1 }],
  success_url: 'https://yoursite.com/success',
  cancel_url: 'https://yoursite.com/cancel',
  metadata: {
    affitor_click_id: clickId,        // from the affitor_click_id cookie
    affitor_customer_key: user.id,    // SAME id you used at signup
    program_id: 'YOUR_PROGRAM_ID',
  },
  // subscriptions: the SAME metadata here reaches the subscription's invoices
  subscription_data: {
    metadata: {
      affitor_click_id: clickId,
      affitor_customer_key: user.id,
      program_id: 'YOUR_PROGRAM_ID',
    },
  },
});
```

### Option B: Server-side tracking (any provider)

Report the finalized sale from your backend. Works with any payment provider.

```ts
import Affitor from '@affitor/sdk/server';
const affitor = new Affitor({ apiKey: process.env.AFFITOR_API_KEY! });

await affitor.trackSale({
  customerExternalId: user.id, // SAME id as signup
  amount: 4999,                // integer cents
  invoiceId: invoice.id,       // idempotency key; a duplicate returns 409
});
```

For a real server-side sale, `customer_key` matches a key already stored on a customer in your program, for example by a server-verified lead or an attributed Stripe payment. If the key has not been stored, send a matching `click_id`; otherwise the request returns `400 Customer not found`.

## Verify

<VerifySuccess
  browser={["Open a partner link from your program. It carries the partner code in the **Partner link parameter** set on the **Tracking** settings page (`?via=` by default for new programs; programs created before October 16, 2026 keep `?aff=`), and the tracker reads both `?via=` and `?aff=`. An `affitor_click_id` cookie is set"]}
  network={["Your server's `trackLead()` call to `POST /api/v1/track/lead` (your Clerk webhook, your NextAuth `/api/affitor/lead` route after sign-in, or your Supabase Edge Function) returns 2xx without `provisional: true`"]}
  dashboard={["The click, lead, and sale appear under your program's tracking events, attributed to the partner"]}
  ifNotWorking={["Create a test lead from your server: `affitor.trackLead({ customerExternalId: 'test_customer', additionalData: { test_mode: true, program_id: YOUR_PROGRAM_ID } })`. For a test sale, call `POST /api/v1/track/sale` directly with your API key and `additional_data: { test_mode: true }`: the SDK's `trackSale()` cannot send it", "Clerk webhook path: if leads are unattributed, confirm `affitor_click_id` is present in `unsafe_metadata` before the webhook fires", "NextAuth: if no lead appears, the click ID is not reaching your server. Confirm the `affitor_click_id` cookie is set before the user signs in"]}
/>

## Common mistakes

<CommonMistakes items={[
  "Different customer IDs at signup vs sale: `affitor_customer_key` must equal the `customer_key`/`customerExternalId` you sent at signup.",
  "Subscriptions missing `subscription_data.metadata`. On your own Checkout Session, put the click in `subscription_data.metadata` so it reaches the invoices. Without a click in invoice metadata, Affitor can still match an existing customer or use a valid Affitor `client_reference_id` from the subscription's Checkout Session, subject to account and program checks.",
  "Loading the tracker on the server: `AffitorProvider` and `loadAffitor()` must run in a client component (on the server they resolve to `null`).",
  "Calling `signup()` in a server component or route handler: it must run in a client component where the cookie is accessible.",
  "Relying on the browser `signup()` alone: by default it stays provisional until your server sends the lead.",
  "Tracking leads from a server-side callback without forwarding the click ID (Clerk's `user.created` webhook, NextAuth's `events.createUser`, a Supabase Edge Function or DB trigger): the browser cookie is not available server-side, so the lead call returns 400 and nothing is recorded. Forward the click ID explicitly, or with NextAuth use the server route in Step 2.",
  "Clerk: reading `getClickId()` too late. Call it before Clerk redirects away from the sign-up page, otherwise the value may not be available in the new page context.",
  "NextAuth: wrapping `AffitorAuthTracker` outside `SessionProvider`. `useSession()` will throw; `SessionProvider` must be an ancestor.",
  "Trying to track a sale from the browser: sales are server-side only (Stripe metadata or the server SDK)."
]} />

<NextStep title="Add Stripe for sales tracking" description="Attach Affitor metadata to Stripe Checkout Sessions so sales and renewals attribute automatically." href="/docs/api-reference/integrations/stripe" />
