Clerk

Discover how to track lead conversion events using Clerk and LinkKit.

Discover how to track lead conversion events using Clerk and LinkKit.

Business Plan Requirement
This feature is only available on LinkKit Business plans and above.

When tracking conversions, a lead event occurs when a user takes an action that shows interest in your product or service. Examples of lead events include:

  • Creating an account
  • Scheduling a demo meeting
  • Subscribing to a mailing list

These actions indicate user intent and help you identify potential customers in your conversion funnel.

In this guide, we'll focus on tracking new user sign-ups for a SaaS application that uses Clerk for user authentication.

Prerequisites

Before you can start tracking conversions, you'll need to enable conversion tracking for your LinkKit links.

Once enabled, LinkKit will be able to capture and attribute user sign-up events to the corresponding link clicks.

LinkKit Partners
If you're using LinkKit Partners, you can skip this step, as partner links have conversion tracking enabled by default.
Option 1: Enable Conversion Tracking at the Workspace Level
To enable conversion tracking automatically for all future links created in a workspace:

Navigate to your workspace's Tracking Settings page.
Turn on the Workspace Conversion Tracking toggle.

After enabling this setting, all new links created within the workspace will have conversion tracking enabled by default.
Option 2: Enable Conversion Tracking at the Link Level
If you don’t want to enable conversion tracking for every link in your workspace, you can enable it individually for specific links.

To enable conversion tracking for a particular link:

Open the LinkKit Link Builder for the link you want to track.
Turn on the Conversion Tracking toggle.

This will enable conversion tracking only for that selected link, giving you more control over which links track conversions.
Option 3: Enable Conversion Tracking via the API
You can also enable conversion tracking programmatically using the LinkKit API.

When creating or updating a link, simply include the trackConversion: true parameter in your API request. This will activate conversion tracking for that link automatically.

Once conversion tracking is enabled, you'll need to install the LinkKit Analytics script on your website to start tracking conversion events.

You can add the LinkKit Analytics script in several different ways depending on your website setup and technical requirements:

Verify the Installation
You can confirm that the LinkKit Analytics script has been installed correctly by running the following checks:

Open your browser’s developer console and enter _linkkitAnalytics.
If the script is installed properly, you should see the _linkkitAnalytics object displayed in the console.
Add the ?linkkit_id=test query parameter to your website URL.
Check that the linkkit_id cookie is being created in your browser.

If both checks are successful, the analytics script has been installed correctly.

If not, verify the following:

The analytics script has been added inside the <head> section of your page.
If you are using a content delivery network (CDN), clear or purge your cached content to ensure the latest changes are being loaded.

Configure Clerk

Next, configure Clerk to track lead conversion events whenever a new user signs up.

Follow the setup steps to connect Clerk with LinkKit and automatically record new user sign-up events as lead conversions. A quick video walkthrough is available to guide you through the process.

Here’s a quick overview of the steps:

1. Add Environment Variables

Add the following environment variables to your application:

# 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 from your LinkKit dashboard
LINKKIT_API_KEY=your_api_key

2. Add a Custom Claim to Your Clerk Session Token

Add the following JSON as a custom claim in your Clerk session token:

{
  "metadata": "{{user.public_metadata}}"
}

3. Extend the @linkkit/analytics Package with Clerk's useUser Hook

Extend the @linkkit/analytics package by integrating Clerk’s useUser hook to access user information.

Add a trackLead server action to the analytics package to send lead conversion events when a user signs up or completes a qualifying action.

"use client";

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

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

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

    // If the user is loaded but hasn't been persisted to LinkKit 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 LinkKitAnalytics component to your app’s root layout component:

import { LinkKitAnalytics } from "@/components/linkkit-analytics";

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

4. Implement the trackLead Server Action

On the server side, implement the trackLead server action to send lead conversion events to LinkKit.

Alternatively, you can create an API route instead of using a server action to handle lead tracking.

// This is a server action
"use server";

import { linkkit } from "@/lib/linkkit";
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 linkkitId = cookieStore.get("linkkit_id")?.value;

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

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

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

    return { ok: true };
  } catch (error) {
    console.error("Error in trackLead:", error);
    return { ok: false, error: (error as Error).message };
  }
}
// This is an API route
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  // Read linkkit_id from the request cookies
  const linkkitId = req.cookies.get("linkkit_id")?.value;

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

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

  const res = NextResponse.json({ ok: true });

  // Delete the linkkit_id cookie
  res.cookies.set("linkkit_id", "", {
    expires: new Date(0),
  });

  return res;
}

Lead Event Properties

The following properties can be included when sending a lead event to LinkKit:

Property

Required

Description

clickId

Yes

The unique ID of the click associated with the lead conversion event. This value can be retrieved from the linkkit_id cookie. If an empty string is provided (for example, when using deferred lead tracking), LinkKit will attempt to find an existing customer using the provided customerExternalId and use the associated clickId if available.

eventName

Yes

The name of the lead event being tracked. This can also be used as a unique identifier to associate a lead event with a customer for a future sale event (using the leadEventName property in /track/sale).

customerExternalId

Yes

The unique identifier of the customer in your system. LinkKit uses this value to identify the customer and attribute future events to them.

customerName

No

The customer's name. If not provided, a random name will be generated.

customerEmail

No

The customer's email address.

customerAvatar

No

The URL of the customer's avatar or profile image.

mode

No

The tracking mode for the lead event. async sends the event without waiting for completion, wait waits until the event is fully recorded, and deferred delays lead event creation until a later request.

metadata

No

Additional information to store with the lead event. Maximum length: 10,000 characters.

Example App

To learn more about tracking lead conversion events with Clerk and LinkKit, check out the example application.

View Your Conversions

Once you’ve completed the setup, all tracked conversion events will appear in LinkKit Analytics.

LinkKit provides three different views to help you monitor and understand your conversion performance:

Time-Series View

Analyze conversion trends over time with a time-series view that displays the number of:

  • Clicks – Total tracked link clicks.
  • Leads – Number of lead conversion events recorded.
  • Sales – Number of completed sales conversions.

This view helps you track growth patterns, measure campaign performance, and understand how users move through your conversion funnel over time.

Funnel Chart View

Visualize your conversion journey with a funnel chart that shows conversion and drop-off rates across each stage of the funnel:

Clicks → Leads → Sales

This view helps you understand how users progress through your conversion funnel, identify where customers are dropping off, and optimize each stage to improve overall conversion performance.

Real-Time Events Stream

Monitor conversion activity as it happens with a real-time events stream that displays every conversion event recorded across all links in your workspace.

This view provides instant visibility into:

  • Lead events as they are captured.
  • Sale events as they occur.
  • Conversion activity and attribution details across all tracked links.

The real-time events stream helps you validate tracking, monitor campaigns, and stay updated on customer conversions in real time.