Refport
SDKs

Better Auth

@refport/better-auth automatically tracks sign-up leads via a Better Auth plugin — no manual track.lead() call required.

@refport/better-auth is a Better Auth plugin that hooks into the user creation lifecycle. When a new user signs up and the refp_id cookie is present in the request, it automatically calls refport.track.lead() and clears the cookie.

Installation

npm install @refport/better-auth
# or
pnpm add @refport/better-auth

Server setup

Add the plugin to your Better Auth configuration:

auth.ts
import { refportPlugin } from '@refport/better-auth';
import { betterAuth } from 'better-auth';
import { Refport } from 'refport';

const refport = new Refport({
  apiKey: process.env.REFPORT_API_KEY!,
});

export const auth = betterAuth({
  // ...your existing config
  plugins: [
    refportPlugin({ refport }),
  ],
});

That's it — every new user account will automatically trigger a lead event if their request contains the refp_id cookie.

Plugin options

OptionTypeDefaultDescription
refportRefportRequired. Your initialised Refport SDK instance
eventNamestring"Sign Up"Event name sent to track.lead()
cookieNamestring"refp_id"Cookie name to read the click ID from
customLeadTrack(user, ctx) => Promise<void>Override the default tracking behaviour entirely

Client setup

Add the client plugin to your Better Auth client initialisation to make the plugin's inference types available:

auth-client.ts
import { refportPluginClient } from '@refport/better-auth/client';
import { createAuthClient } from 'better-auth/client';

export const authClient = createAuthClient({
  plugins: [
    refportPluginClient(),
  ],
});

How it works

The plugin registers a databaseHooks.user.create.after hook in Better Auth. After a user row is inserted:

  1. It reads the refp_id cookie from the request context
  2. If found, it calls refport.track.lead() with the user's ID, email, and name
  3. It clears the cookie by setting it to an expired value
  4. If tracking fails, the error is logged but does not interrupt the sign-up flow

Custom tracking logic

Pass customLeadTrack if you need to send additional metadata or use a different identifier:

refportPlugin({
  refport,
  customLeadTrack: async (user, ctx) => {
    const clickId = ctx.getCookie('refp_id');
    if (!clickId) return;

    await refport.track.lead({
      clickId,
      eventName: 'Account Created',
      customerExternalId: user.id,
      customerEmail: user.email,
      metadata: { plan: 'free' },
    });
  },
}),

The refp_id cookie is set by refport-js on the frontend. Make sure you call init() (or use <RefportTracker>) on every page so clicks are captured before the user reaches the sign-up form.

On this page