Skip to Content
Developer DocsConversion trackingLeadsNextAuth.js

// snippet import removed // snippet import removed // snippet import removed // snippet import removed

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

Configure NextAuth.js Options

Then, set up your NextAuth.js configuration options to track lead conversion events using the dub TypeScript SDK.

Here’s how it works in a nutshell:

  1. Use NextAuth’s signIn event to detect when there’s a new sign up.
  2. If the user is a new sign up, check if the dub_id cookie is present.
  3. If the dub_id cookie is present, send a lead event to Dub using dub.track.lead
  4. Delete the dub_id cookie.

Under the hood, Dub records the user as a customer and associates them with the click event that they came from. The user’s unique ID is now the source of truth for all future events – hence why we don’t need the dub_id cookie anymore.

// app/api/auth/[...nextauth]/options.ts import type { NextAuthOptions } from "next-auth"; import { cookies } from "next/headers"; import { dub } from "@/lib/dub"; export const authOptions: NextAuthOptions = { ...otherAuthOptions, // your other NextAuth options events: { async signIn(message) { // if it's a new sign up if (message.isNewUser) { const cookieStore = await cookies(); // check if dub_id cookie is present const dub_id = cookieStore.get("dub_id")?.value; if (dub_id) { // send lead event to Dub await dub.track.lead({ clickId: dub_id, eventName: "Sign Up", customerExternalId: user.id, customerName: user.name, customerEmail: user.email, customerAvatar: user.image, }); // delete the cookies cookieStore.delete("dub_id"); cookieStore.delete("dub_partner_data"); } } }, }, };
💡

In NextAuth.js, the isNewUser flag will only be available if you’re using next-auth’s database implementation (otherwise it’ll return undefined). In that case, you should move the logic above to the signIn callback instead.

Create a NextAuth.js Route Handler

Finally, import the authOptions variable you created earlier and use NextAuth to create a handler for your NextAuth.js routes.

// app/api/auth/[...nextauth]/index.ts import { authOptions } from "./options"; import NextAuth from "next-auth"; const handler = NextAuth(authOptions); export { handler as GET, handler as POST };