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

# Clerk

> Learn how to track lead conversion events with Clerk and CodeQR

> [!NOTE]
>
> Conversion tracking requires a [Pro plan](https://codeqr.io/pricing)
> subscription or higher (or an active conversion trial).

When it comes to [conversion tracking](https://docs.codeqr.io/conversions/quickstart), a `lead` event happens when a user performs an action that indicates interest in your product or service. This could be anything from:

* Signing up for an account
* Adding a product to cart
* Joining a mailing list

![A diagram showing how lead events are tracked in the conversion funnel](https://assets.codeqr.io/help/conversion-lead-event.png)

In this guide, we will be focusing on tracking new user sign-ups for a SaaS application that uses Clerk for user authentication.

## Prerequisites

Before you get started, make sure you follow the [CodeQR Conversions quickstart guide](https://docs.codeqr.io/conversions/quickstart) to get CodeQR Conversions set up for your links:

1. [Enable conversion tracking for your links](https://docs.codeqr.io/conversions/quickstart#step-1-enable-conversion-tracking-for-your-links)
2. [Install the @codeqr/analytics client-side SDK](https://docs.codeqr.io/sdks/client-side/introduction.md)
3. [Install the CodeQR server-side SDK](https://docs.codeqr.io/conversions/quickstart#step-3-install-the-codeqr-server-side-sdk)

## Configure Clerk

Next, configure Clerk to track lead conversion events when a new user signs up. Here's a quick video showing how to do this:

[Loom video player](https://www.loom.com/embed/7338589f0c0c4ee1b71c9f2aa28aac87?sid=04c67f3b-1bec-468a-b0c7-5b24d24cd96e)

Here's a quick summary of the steps:

**1. Add environment variables**

Add the following environment variables to your app:

```bash theme={null}
# get it here: https://dashboard.clerk.com/apps/new
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=your_publishable_key
CLERK_SECRET_KEY=your_secret_key

# get it here: https://d.to/tokens
CODEQR_API_KEY=your_api_key
```

**2. Add a custom claim to your Clerk session token**

Add the following JSON as a [custom claim](https://clerk.com/docs/references/nextjs/add-onboarding-flow#add-custom-claims-to-your-session-token) to your Clerk session token:

```json Clerk Session Token theme={null}
{
  "metadata": "{{user.public_metadata}}"
}
```

**3. Extend the `@codeqr/analytics` package with Clerk's `useUser` hook**

Extend the [`@codeqr/analytics` package](https://docs.codeqr.io/sdks/client-side/introduction) to include a `trackLead` server action.

```tsx components/codeqr-analytics.tsx theme={null}
"use client";

import { trackLead } from "@/actions/track-lead";
import { useUser } from "@clerk/nextjs";
import { Analytics, AnalyticsProps } from "@codeqr/analytics/react";
import { useEffect } from "react";

export function CodeQRAnalytics(props: AnalyticsProps) {
  const { user } = useUser();

  useEffect(() => {
    if (!user || user.publicMetadata.codeqrClickId) return;

    // if the user is loaded but hasn't been persisted to CodeQR yet, track the lead event
    trackLead({
      id: user.id,
      name: user.fullName!,
      email: user.primaryEmailAddress?.emailAddress,
      avatar: user.imageUrl,
    }).then(async (res) => {
      if (res.ok) await user.reload();
      else console.error(res.error);
    });

    // you can also use an API route instead of a server action
    /*
    fetch("/api/track-lead", {
      method: "POST",
      body: JSON.stringify({
        id: user.id,
        name: user.fullName,
        email: user.primaryEmailAddress?.emailAddress,
        avatar: user.imageUrl,
      }),
    }).then(res => {
      if (res.ok) await user.reload();
      else console.error(res.statusText);
    });
    */
  }, [user]);

  return <Analytics {...props} />;
}
```

Then, add the `CodeQRAnalytics` component to your app's root layout component:

```tsx app/layout.tsx theme={null}
import { CodeQRAnalytics } from "@/components/codeqr-analytics";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        <CodeQRAnalytics />
        {children}
      </body>
    </html>
  );
}
```

**4. Implement the `trackLead` server action**

On the server side, implement the `trackLead` server action. Alternatively, you can also create an API route instead:

```tsx /actions/track-lead.ts theme={null}
// This is a server action
"use server";

import { codeqr } from "@/lib/codeqr";
import { clerkClient } from "@clerk/nextjs/server";
import { cookies } from "next/headers";

export async function trackLead({
  id,
  name,
  email,
  avatar,
}: {
  id: string;
  name?: string | null;
  email?: string | null;
  avatar?: string | null;
}) {
  try {
    const cookieStore = await cookies();
    const codeqrId = cookieStore.get("cq_id")?.value;

    if (codeqrId) {
      // Send lead event to CodeQR
      await codeqr.track.lead({
        clickId: codeqrId,
        eventName: "Sign Up",
        customerExternalId: id,
        customerName: name,
        customerEmail: email,
        customerAvatar: avatar,
      });

      // Delete the cq_id cookie
      cookieStore.set("cq_id", "", {
        expires: new Date(0),
      });
    }

    const clerk = await clerkClient();
    await clerk.users.updateUser(id, {
      publicMetadata: {
        codeqrClickId: codeqrId || "n/a",
      },
    });

    return { ok: true };
  } catch (error) {
    console.error("Error in trackLead:", error);
    return { ok: false, error: (error as Error).message };
  }
}
```

```tsx /api/track-lead/route.ts theme={null}
// This is an API route
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  // read cq_id from the request cookies
  const codeqrId = req.cookies.get("cq_id")?.value;
  if (codeqrId) {
    // Send lead event to CodeQR
    await codeqr.track.lead({
      clickId: codeqrId,
      eventName: "Sign Up",
      customerExternalId: id,
      customerName: name,
      customerEmail: email,
      customerAvatar: avatar,
    });
  }

  const clerk = await clerkClient();
  await clerk.users.updateUser(id, {
    publicMetadata: {
      codeqrClickId: codeqrId || "n/a",
    },
  });
  const res = NextResponse.json({ ok: true });
  // Delete the cq_id cookie
  res.cookies.set("cq_id", "", {
    expires: new Date(0),
  });
  return res;
}
```

Here's the full list of attributes you can pass when sending a lead event:

| Property | Required | Description |
| :- | :- | :- |
| `clickId` | **Yes** | The unique `cq_id` parameter that the lead conversion event is attributed to. |
| `eventName` | **Yes** | The name of the event. Example: "Sign up". |
| `customerExternalId` | **Yes** | The unique ID of the customer in your system. Will be used to identify and attribute all future events to this customer. |
| `customerEmail` | No | The email address of the customer. |
| `customerName` | No | The name of the customer. If not passed, a random name will be generated (e.g. "Big Red Caribou"). |
| `customerAvatar` | No | The avatar URL of the customer. |

## Example App

To learn more about how to track leads with Clerk, check out the following example app:

> [card] [CodeQR + Clerk Example App](https://github.com/codeqr-io/examples/tree/main/conversions/clerk)
>
> See how to track new user sign-ups with Clerk and the CodeQR SDK.

## View your conversions

Once you've enabled conversion tracking for your links, all your tracked conversions will show up on your [Analytics dashboard](https://app.codeqr.io/analytics). We provide 3 different views to help you understand your conversions:

* **Time-series**: A [time-series view](https://codeqr.io/help/article/codeqr-analytics#1-time-series-analytics-chart) of the number clicks, leads and sales.

![Time-series line chart](https://mintcdn.com/codeqr/Dit-PkrrSHQLOViA/images/conversions/timeseries-chart.png?fit=max\&auto=format\&n=Dit-PkrrSHQLOViA\&q=85\&s=c7bac376603cd71f967f5f7b33f3cadc)

* **Funnel chart**: A funnel chart view visualizing the conversion & dropoff rates across the different steps in the conversion funnel (clicks → leads → sales).

![Funnel chart view showing the conversion & dropoff rates from clicks → leads → sales](https://mintcdn.com/codeqr/Dit-PkrrSHQLOViA/images/conversions/funnel-chart.png?fit=max\&auto=format\&n=Dit-PkrrSHQLOViA\&q=85\&s=001b9b2dad0f759c4031d81122069a75)

* **Real-time events stream**: A [real-time events stream](https://codeqr.io/help/article/real-time-events-stream) of every single conversion event that occurs across all your links in your project.

![The Events Stream dashboard on CodeQR](https://mintcdn.com/codeqr/Dit-PkrrSHQLOViA/images/conversions/events-table.png?fit=max\&auto=format\&n=Dit-PkrrSHQLOViA\&q=85\&s=93b55a350e472e6d7fbafa7e082bbc69)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.