@refrefhq/better-auth
v0.1.1
Published
Better Auth plugin for RefRef: track signups and referrals from your projects that use Better Auth.
Readme
@refrefhq/better-auth
The RefRef plugin for Better Auth. It sends the signup of each new account to RefRef and connects it to the browser's referral click at the moment of account creation. It needs no client secret, signs nothing, and stores nothing in your database. Add the landing script to the pages where a referral link lands; it keeps the browser's referral handle in the refref_handle cookie.
The setup guide is refref.ai/docs/platform/better-auth.
Install
npm install @refrefhq/better-authbetter-auth 1.7.6 or later is a peer dependency. Node.js ^20.19.0 || >=22.12.0 is required.
Use
import { betterAuth } from "better-auth";
import { refrefAnalytics } from "@refrefhq/better-auth";
export const auth = betterAuth({
// ...your configuration
plugins: [
refrefAnalytics({
apiUrl: "https://api.refref.ai",
apiKey: process.env.REFREF_API_KEY!,
projectId: process.env.REFREF_PROJECT_ID!,
resolveSignup: async ({ user }) => ({
participant: { kind: "individual", externalId: user.id },
actor: { kind: "individual", externalId: user.id },
}),
}),
],
});apiUrl is required. Keep the API key on your server. The resolver names the participant of the signup by its kind and the tenant's external ID: the user, or a group such as the user's workspace. The plugin does not assume that the user is the participant. Return the same participant for every call about one user. The actor is optional and is always an individual. The plugin adds the Project, occurredAt (the creation time of the account or the organization, unless the resolver gives one), and identify. A signup needs no sourceEventId: RefRef derives one key for each participant, so a repeated signup converges (API).
Milestones
| milestone | At the creation of the account | Later |
| --------------------------- | ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| account-created (default) | One signup with identify: { handle } | Nothing |
| email-verified | POST /v1/identify { handle, reference }; no signup | At the first verified state of the email, the signup, with occurredAt = the account creation (below) |
| group-created | Nothing | At /organization/create of the organization plugin, the signup of the group with the creator's handle; members never identify |
- In
email-verifiedmode, an account that is verified when it is created signs up at once, in one call: a social account with a verified email, a magic link, or an email code. A later verification of the same user, for example after an email change, sends the same signup again, and RefRef keeps the first. - In
group-createdmode, the resolver getsorganization(id,name,slug) and the creator asuser(id). It names the group participant. The mode does not check the creator's email. To count only groups of verified creators, setemailAndPassword.requireEmailVerification, so that an email and password user signs in, and can create an organization, only after the verification.
Accounts that another person created
Anyone can create an account with an email that is not theirs. The owner of the email can later take the account over: Better Auth then removes the access that was created before the proof (a magic link or an email sign-in code), or the owner resets the password.
- In
email-verifiedmode, the creation identifies the creating browser to a reference, not to the participant. Its key is an HMAC, with the Better Auth secret, of the user ID, the email, and the password hash of the credential account. Only the creator's own verification resolves it:/verify-emailor/email-otp/verify-email, before the signup, while the password is the one of the creation, within 30 days. When another proof verifies the email (/magic-link/verify,/sign-in/email-otp, or/email-otp/reset-password), the plugin sends the signup with the handle of the browser that gives the proof, and the creating browser counts for nobody. A password reset before the verification also stops the creating browser from counting. So the creator loses the click when it signs in with a magic link or resets its password before it verifies. - In
account-createdmode, the creation is the signup, and it identifies the creating browser to the participant at once. If the owner of the email takes the account over later, the participant keeps the referral of the browser that created the account. Useemail-verifiedfor a Project that pays referrer Rewards.
Which requests identify
- The plugin uses the
user.create.afterdatabase hook, so every creation method identifies: email and password, social sign-up, magic link, email code, or another plugin. - Only a creation request with a
refref_handlecookie that holds a handle ID identifies. A request without it, such as a creation that your backend makes, identifies nothing. A request of a signed-in user, such as an admin who creates an account for another person, identifies nothing. - A user of the Better Auth anonymous plugin (
isAnonymous) identifies nothing and sends no signup: an anonymous session is not an account creation. A request with an anonymous session still counts as a visitor, so the real account that the person later creates identifies the browser's handle. - Sign-in, the creator's verification, account linking, and joining an organization never identify. In
email-verifiedmode, a proof that takes over an account that another person created identifies the browser that gives it (above).
Magic link and email code on another device
A person can ask for a magic link or an email code in one browser and complete it on another device. Then the creation request does not have the starting browser's cookie, so the plugin uses a reference:
- When
/sign-in/magic-linkor/email-otp/send-verification-otp(typesign-in) makes a challenge for an email that has no account, the plugin identifies the browser's handle toreference: { key }. The key is an HMAC-SHA256, with the Better Auth secret, of the stored magic-link token, or of the email code and its identifier. It never leaves your server, and it shows RefRef no token, code, or email. - When
/magic-link/verifyor/sign-in/email-otpconsumes the challenge and creates the account, the plugin resolves the reference to the participant first. Then it sends the signup with the handle of the browser that completes the flow. So the starting browser's click counts on any device, and a completion in the starting browser identifies the same handle again.
The reference expires 24 hours after the first call (the RefRef default); the challenge expires earlier. Limits:
- A handle is identified once. A resend makes a new challenge, and the handle stays with the first one: the click counts only when the person completes the first link or code. An earlier magic link stays valid until it expires; an earlier code does not.
- The plugin sees a consumed challenge only through the delete hook of a verification row in the database. With
secondaryStorageand withoutverification.storeInDatabase, the plugin uses no reference; a completion in the starting browser still identifies at creation. - With
emailOTP({ resendStrategy: "reuse" }), Better Auth gives the code of the first request to every browser that asks for one while it is valid, so the code does not belong to one browser. The plugin then uses no reference for email codes; magic links keep theirs, and a code that completes in the browser that asked for it still identifies that browser at creation. group-createdmode uses no reference.
Server-set cookie
Safari keeps a cookie that a script writes for 7 days only. POST <basePath>/refref/handle (auth.api.refreshRefRefHandle) sets refref_handle again from the server, with the value that the request carries: Path=/, Max-Age 90 days, SameSite=Lax, Secure when the Better Auth base URL uses HTTPS, not HttpOnly (the landing script must read it), and Domain. The Domain is the cookieDomain option, or else the registrable domain of the Better Auth base URL (app.example.co.uk gives example.co.uk), which is the domain that the landing script uses by default. When the landing script sets data-cookie-domain, give cookieDomain the same value. The response is { handle }, or { handle: null } when the request has no handle ID; then the endpoint sets no cookie. It never creates or changes a handle. Call it after capture, on the host of the auth server:
await window.RefRefAttribution.capture();
await fetch("/api/auth/refref/handle", { method: "POST" });Failures and retries
- Sign-up never fails because of RefRef. The calls of one moment run in order, after Better Auth commits the user. With
advanced.backgroundTasks.handler, they run in the background; otherwise the request waits for them. - Each call is tried up to three times when it gets no response, a timeout (3 seconds), a 429, or a 5xx status, after 100 ms and 400 ms. Every call is safe to repeat: a handle is identified once, a reference resolves once, and a repeated signup converges.
- An identification that RefRef refuses with 404 or 409 (a cookie value that is not a handle of the Project, a handle that is already identified, or an expired reference) identifies nothing and is no error. On a signup, RefRef answers with
identified: falseinstead. - A signup never waits for a later identification. So when the resolve of a reference fails after its retries, the plugin does not send the signup of that moment:
onErrorgets theidentifydelivery and then thesignupdelivery, with the same error. Send them again in that order, so the signup sees the starting browser's click. onError(error, delivery)gets every other failure. The default logs it with the Better Auth logger.erroris aRefRefAPIErrorwithstatusandcodeof the error body when RefRef answered. Keepdeliveryto send it again later withRefRefAPIClient.deliver(delivery). When the resolver throws,deliveryis undefined. This plugin is not a durable outbox.
RefRefAPIClient also sends a canonical purchase with trackPurchase (type: "purchase", exact integer minor units) and an identification with identify (POST /v1/identify). It validates each body before it sends it.
License
MIT
