Skip to Content
better-auth-plugins

Referral

Referral codes, sign-up attribution, and reward steps.

The referral plugin gives users a code to share, records who signed up with whose code, and tells you when a referral counts, so you can reward it.

  • Attributes every way a user signs up: email and password, social sign-in, magic link, email OTP.
  • Steps before a referral counts, such as a verified email or a first purchase, so fake accounts don't earn rewards. Apps that send verification emails require a verified email by default.
  • onReferralCompleted runs when a referral completes: grant the reward there. Failed calls can be retried from a cron job (see Delivering rewards).
  • Referrers see who they referred with masked emails; codes don't reveal whose they are.

Installation

Install the package

npm install @checodo/better-auth-referral

Add the plugin to your auth config

auth.ts
import { betterAuth } from "better-auth";
import { referral } from "@checodo/better-auth-referral";

export const auth = betterAuth({
  plugins: [
    referral({
      onReferralCompleted: async ({ referrerUserId }) => {
        await grantCredit(referrerUserId);
      },
    }),
  ],
});

Migrate the database

The plugin adds the referralCode, referral, referralStep, and referralSlot tables (see Schema).

npx auth@latest migrate

Add the client plugin

auth-client.ts
import { createAuthClient } from "better-auth/client";
import { referralClient } from "@checodo/better-auth-referral/client";

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

Usage

Share a code

Every user can have one code. Create it when they open your "invite friends" page, or for every new user with createCodeOnSignUp: true:

const { data } = await authClient.referral.createCode();
// data: { code: "K7MPX2QD" } (the same code on every call)

const shareUrl = `https://example.com/sign-up?ref=${data?.code}`;

// read it without creating one
const { data: existing } = await authClient.referral.getCode();
// existing: { code: string | null }

Codes are 8 characters (codeLength) of consonants and digits, and case-insensitive. They have no look-alikes such as 0/O and 1/I, and no vowels, so a random code can't spell a word, offensive ones included. To use your own format, pass generateCode; collisions are retried.

A user who wants a new code (because a link was shared too widely, say) can replace theirs. The old code and every link with it stop working at once; users who already signed up with it stay their referrals:

const { data } = await authClient.referral.regenerateCode();
// data: { code: "R4TQW9HZ" }

Sign up with a code

Pass the code with the request that creates the user. It is read from the x-referral-code header, from additionalData.referralCode of a social sign-in, or from a referralCode field in the sign-up body:

// email and password
await authClient.signUp.email(
  { email, password, name },
  { headers: { "x-referral-code": code } },
);

// social sign-in: the code survives the redirect to the provider
await authClient.signIn.social({
  provider: "github",
  additionalData: { referralCode: code },
});

// magic link, email OTP, phone number, Sign-In with Ethereum, ...:
// the header on the request that creates the user
await authClient.signIn.emailOtp(
  { email, otp },
  { headers: { "x-referral-code": code } },
);

The header is the typed way for better-auth's client. The referralCode body field is for plain HTTP requests, such as an HTML form posting to /sign-up/email.

Auth server on another domain?

x-referral-code is a custom header. If your app and your auth server run on different origins, the browser only sends it when the server's CORS configuration allows it (Access-Control-Allow-Headers). Add the header there. Social sign-in (additionalData) and the body field need no extra header.

Invalid codes

A code that doesn't exist, whose owner has referred maxReferralsPerUser users already, or whose owner is banned (see Fraud checks) is invalid. By default (invalidCode: "ignore") the user signs up anyway, without a referral: a typo in an optional field shouldn't cost anyone their sign-up. With invalidCode: "reject" the sign-up fails with INVALID_REFERRAL_CODE instead.

The sign-up itself can't carry a warning, so let the form check the code when it is submitted, and ask before signing up without one:

type SignUpForm = { email: string; password: string; name: string; code?: string };

async function onSubmit({ email, password, name, code }: SignUpForm) {
  if (code) {
    const { data } = await authClient.referral.checkCode({ query: { code } });
    if (!data?.valid && !confirm("This referral code is invalid. Sign up without it?")) return;
  }
  await authClient.signUp.email(
    { email, password, name },
    code ? { headers: { "x-referral-code": code } } : undefined,
  );
}

checkCode doesn't say whose code it is. Check on submit (or when the field loses focus), not on every keystroke: it is rate limited (see Rate limits).

A user is referred at most once, by the first code they sign up with.

Steps and rewards

A referral starts pending when the referred user signs up, and becomes completed once every step in steps is done. Without steps, it completes at sign-up.

Rewards need at least email-verified

If a referral completes at sign-up, anyone can earn rewards by signing up fake accounts with their own code. Require at least "email-verified", so every referred account needs a real inbox.

The default depends on your auth config:

Your configDefault steps
emailVerification.sendVerificationEmail is set["email-verified"]
otherwise[]

Without verification emails, email-and-password users can never verify, so requiring it would leave their referrals pending forever. If you verify emails another way, for example with the email OTP plugin's overrideDefaultEmailVerification, the default can't tell: set steps: ["email-verified"] yourself. Passing steps yourself always wins. When the default leaves steps empty and onReferralCompleted is set, the plugin logs a warning at startup. An explicit steps: [] doesn't warn: that's a choice.

auth.ts
referral({
  steps: ["email-verified", "first-purchase"],
  onStepCompleted: ({ referral, step }) => {
    console.log(`${referral.referredUserId} completed ${step}`);
  },
  onReferralCompleted: async (referral) => {
    // can run again on a retry: key the reward on referral.id
    await grantCredit(referral.referrerUserId, { idempotencyKey: referral.id });
  },
});
  • email-verified is recorded by the plugin when the referred user's email is verified. Social sign-ins usually verify the email at once.
  • Your own steps are recorded by your server, for example in a payment webhook:
server
await auth.api.completeReferralStep({
  body: {
    userId: order.userId,
    step: "first-purchase",
    metadata: { orderId: order.id }, // optional, stored as JSON
  },
});
// { referral: { status, steps, ... } }, or { referral: null } if the user wasn't referred

completeReferralStep is server only: it has no HTTP route, so clients can't complete steps themselves. Each step counts once; recording it again changes nothing. Steps that aren't in steps fail with UNKNOWN_REFERRAL_STEP.

Delivering rewards

A referral is saved as completed in a single conditional update, so however many requests complete its last step at once, only one of them calls onReferralCompleted, right after that update. The referral records the call: rewardStatus is "pending" until the callback returns without an error, then "rewarded".

If the callback throws, the error is logged and the referral stays "pending"; if the process stops before the callback returns, too. Call retryReferralRewards regularly, for example every few minutes from a cron job, to call it again for those referrals:

server
// e.g. in a cron route
const { attempted, rewarded } = await auth.api.retryReferralRewards({
  body: { limit: 50 }, // optional, at most 500
});
  • A call is retried once rewardRetry.delay (5 minutes by default) has passed since it started, so a call still running isn't started again. Set it longer than your callback can take.
  • After rewardRetry.maxAttempts calls (10 by default), a referral is left "pending" and no longer retried. Find those with listAllReferrals (rewardStatus and rewardAttempts are in each referral) to look into them. With the audit log, the last failed call is also recorded as referral.reward-failed (severity high), once each time a referral's attempts run out, so its onEvent can alert you. Raising maxAttempts later retries those referrals, and records another event if they fail again. A last call that never finishes isn't recorded.
  • Concurrent retries don't call the callback twice for the same attempt: each takes the referral with a conditional update first.
  • Referrals completed without onReferralCompleted set, or before this was tracked, have no rewardStatus and are never retried, so setting the callback later doesn't pay out old referrals.
  • retryReferralRewards is server only, like completeReferralStep.

Delivery is at least once: if the process stops after your callback granted the reward but before the referral was marked "rewarded", the next retry calls it again. Make the reward idempotent, keyed on referral.id, so granting it twice credits once.

onReferral and onStepCompleted are not tracked or retried: if they throw, the error is logged.

Your referrals

Signed-in users see who they referred, newest first: their name and email. Emails are masked (b***@example.com) unless maskEmails is false, and names are left out with hideNames: true. Mention in your privacy policy what referrers see. The response has no user ids:

const { data } = await authClient.referral.listReferrals({
  query: { status: "completed", limit: 20, offset: 0 }, // all optional
});
// data: {
//   referrals: [{ id, status, steps, createdAt, completedAt, referredUser: { name, email } }],
//   total,      // with the status filter
//   completed,  // completed referrals in total
// }

To not show referrers who they referred at all, turn the endpoint off with better-auth's disabledPaths:

auth.ts
betterAuth({
  disabledPaths: ["/referral/list-referrals"],
});

Fraud checks

Rewards make referrals worth faking. steps is the first line of defense: a referral only counts once the referred user has done something real. For more, decide per sign-up with allowReferral; returning false signs the user up without a referral:

auth.ts
referral({
  allowReferral: async ({ referrerUserId, referredUser, context }) => {
    // e.g. your own checks: same IP address, disposable email, ...
    return !(await looksLikeSelfReferral(referrerUserId, referredUser, context?.headers));
  },
});

If allowReferral throws, the error is logged and the user signs up without a referral.

Also consider:

  • maxReferralsPerUser, so one user can't earn unlimited rewards. It counts across all their codes, so regenerateCode doesn't reset it, and it holds when sign-ups with the same code happen at the same time, in whatever order their transactions commit: once the user is saved, the referral takes one of the referrer's places, each a row with a unique key in referralSlot, and is dropped if none is free. When sign-ups race for the last place, the first to settle gets it (at worst none does, and the place stays free for the next sign-up). A sign-up that loses is a normal sign-up without a referral (onReferral doesn't run), even with invalidCode: "reject", since the user exists by then. Referrals made before the limit was set count toward it. Lowering the limit doesn't remove referrals already made; a referral deleted with its user frees its place.
  • Banning fraudsters with better-auth's admin plugin: a banned user's code stops working until the ban ends, so new sign-ups no longer count for them. Referrals they made before the ban can still complete, so check the referrer in onReferralCompleted before paying out.
  • The blocklist plugin with its disposable email domains, so throwaway addresses can't sign up (and verify) at all. A sign-up the blocklist stops creates no user, so no referral is recorded and no reward is paid.
  • Granting rewards only for steps that cost the referred user something, like a purchase.

Rate limits

/referral/check-code is the only endpoint anyone can call. It is limited to 5 requests per minute per IP by better-auth's rate limiter, which is on in production by default, so codes can't be guessed quickly. Change it with rateLimit.customRules:

auth.ts
betterAuth({
  rateLimit: {
    customRules: { "/referral/check-code": { window: 60, max: 10 } },
  },
});

More than one server? Share the rate limit's storage

better-auth counts requests in memory by default, per server process. With several instances or serverless functions, every instance keeps its own count, so the real limit is 5 per minute per instance and barely slows down guessing. Store the counts where all instances see them, with rateLimit.storage: "database" or "secondary-storage" (Redis, for example). The limiter is also off in development unless you set rateLimit.enabled: true.

When things fail

Referrals never break sign-up: if recording a referral fails, or a callback throws, the error is logged and the user is signed up anyway. Only onReferralCompleted can be retried (see Delivering rewards). The referral is recorded only after the sign-up has been saved: if the sign-up fails, no referral is recorded and no callback runs.

With the audit log

With the audit log plugin, new and completed referrals, and rewards that failed for the last time, are recorded there too (see Events from other plugins).

Admins

Users with one of adminRoles (the role field of better-auth's admin plugin) or listed in adminUserIds can list all referrals, with full user ids. Requests without a session get a 401, other users a 403.

const { data } = await authClient.referral.listAllReferrals({
  query: { referrerUserId: "user-id", status: "pending", limit: 20, offset: 0 },
});
// data: { referrals: [{ id, referrerUserId, referredUserId, code, status, steps, ... }], total }
EndpointClientServer
GET /referral/get-codeauthClient.referral.getCodeauth.api.getReferralCode
POST /referral/create-codeauthClient.referral.createCodeauth.api.createReferralCode
POST /referral/regenerate-codeauthClient.referral.regenerateCodeauth.api.regenerateReferralCode
GET /referral/check-codeauthClient.referral.checkCodeauth.api.checkReferralCode
GET /referral/list-referralsauthClient.referral.listReferralsauth.api.listReferrals
GET /referral/list-all-referralsauthClient.referral.listAllReferralsauth.api.listAllReferrals
(server only)-auth.api.completeReferralStep
(server only)-auth.api.retryReferralRewards

Schema

Table: referralCode

Prop

Type

Table: referral

Prop

Type

Table: referralStep

Prop

Type

The places of maxReferralsPerUser are only written when it is set.

Table: referralSlot

Prop

Type

To rename the tables or their columns, use the schema option:

auth.ts
referral({
  schema: {
    referral: { modelName: "referrals", fields: { createdAt: "created_at" } },
  },
});

Error codes

Exported as REFERRAL_ERROR_CODES from both entry points, to compare with error.code:

import { REFERRAL_ERROR_CODES } from "@checodo/better-auth-referral/client";

if (error?.code === REFERRAL_ERROR_CODES.INVALID_REFERRAL_CODE.code) {
  // show "This invite link has expired"
}
CodeStatusWhen
INVALID_REFERRAL_CODE400Signing up with an unusable code, with invalidCode: "reject"
UNKNOWN_REFERRAL_STEP400completeReferralStep with a step that isn't in steps
METADATA_TOO_LARGE400completeReferralStep with more than 2,000 characters of JSON
CODE_GENERATION_FAILED500createCode or regenerateCode when 5 generated codes in a row were taken
YOU_ARE_NOT_ALLOWED_TO_LIST_REFERRALS403listAllReferrals, for users who aren't admins

Options

Prop

Type

Reward retry options

Prop

Type

On this page