---
title: "Run a referral program"
description: "Give every person a referral link, attribute sign-ups through an explicit claim with nothing stored on the device, and reward both sides from your catalog once the referred person's first payment clears its hold, with caps and abuse checks."
canonical_url: "https://nuxt-backend.dev/docs/build/growth/offers/referrals"
---
# Run a referral program

> Give every person a referral link, attribute sign-ups through an explicit claim with nothing stored on the device, and reward both sides from your catalog once the referred person's first payment clears its hold, with caps and abuse checks.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

A referral program pays people back for bringing paying customers. Each person gets a link with a code of their own. Someone who signs up through it claims the referral, and once their first payment clears its hold, both sides get the reward your program names: a discount or trial days for the person referred, credits or free months for the person who referred them. Rewards are things your catalog already sells. They are never cash, and the package keeps no ledger of them.

- **Natively:** Polar has no referral program. It applies discounts and trials at checkout, grants a pack's credits on a paid or $0 order, moves a subscription's renewal date, and reports refunds by webhook (checked on 2026-10-25).
- **The package adds:** a code per person, the claim step through sign-in, the hold, caps and abuse checks, rewards granted through Polar, the share loop on public share pages, and an admin view.

## Before you start

- The rewards in your catalog: a [promotion](https://nuxt-backend.dev/docs/build/growth/offers) without a code for the person referred, and a [credit pack](https://nuxt-backend.dev/docs/build/billing/credits) or a plan for the referrer.
- Billing set up with `setupBilling`: [Set up billing](https://nuxt-backend.dev/docs/build/billing/setup).

## Set up the program

`setupReferrals` from `nuxt-backend/billing` sets the program up in its own backend file:

```ts [backend/referrals.ts]
import { setupReferrals } from 'nuxt-backend/billing'
import { DAY } from 'nuxt-backend/rate-limit'
import { components } from './_generated/api'
import { billing } from './billing'

export const referrals = setupReferrals(components, {
  billing,
  rewards: {
    referred: { discount: 'friend' },     // a catalog discount without a code, or { trialDays: 14 }
    referrer: { pack: 'credits100' },     // a credit pack, or { months: 1 } of their plan
  },
  hold: 30 * DAY,
  caps: { perReferrer: 20, perMonth: 500 },
})

// The functions behind useReferrals, the page a referral link opens, the admin view and the sweep.
export const {
  getReferralCode, getReferrals, claimReferral, previewReferral, setReferralSharing,
  getReferralConsole, resolveReferral, runReferralSweep,
} = referrals.api
```

The options:

- **billing**: the app's `setupBilling` instance. It grants the rewards and reports payments and refunds.
- **rewards**: what each side gets. For the person referred, a catalog discount on their first paid checkout, or trial days on it (30 at most). For the referrer, a credit pack, or free months of their plan (`{ months: 1 }`). A referrer on the free plan gets the pass of a plan with `gift: { months }` in the catalog; name it with `{ months: 1, plan: 'pro' }` when there are several.
- **hold**: how long a reward waits after the first payment, so a refund within the window voids it. Thirty days by default, and never shorter than 14, the withdrawal period in the EU: a shorter one is raised to 14.
- **caps**: how many rewards one referrer earns (`perReferrer`), and how many the program grants in a month (`perMonth`).

With no `rewards`, the program still attributes sign-ups, so you can see what it brings before you pay for it. A referral whose hold ends with no referrer reward is recorded and counted, takes no slot under the caps and reads as `claimed`; one claimed before you named a referrer reward gets the program's reward when its hold ends. The sweep that grants rewards is `runReferralSweep`, which the component's hourly cron wakes: export it with the rest. A reward the catalog cannot back (a discount it does not have, or one that needs a typed code, or a pack it does not sell) is logged and left out until it can ([Troubleshooting](https://nuxt-backend.dev/docs/ship/operate/troubleshooting)).

## Share a code

Each person's code is made the first time they ask for it. The code is the same kind everywhere: a person on the [waitlist](https://nuxt-backend.dev/docs/build/growth/launch/waitlist) already has one, and it becomes their referral code when their address signs up. They share it as a link to `/r/<code>`, or as `?ref=<code>` on the waitlist's page. `<ReferralCard>` shows the link with copy and share buttons, how many friends it brought, and the choice to carry the code on the pages they share. Its default share text says what both sides get, as endorsement rules ask. People share their own link: the app never emails someone without an account on their behalf.

For a page of your own, `useReferrals()` returns the same data:

```vue [app/pages/invite-friends.vue]
<script setup lang="ts">
const { link, shareText, referrals, isLoading } = useReferrals()
</script>

<template>
  <ReferralCard />
  <p v-if="!isLoading">{{ referrals?.rewarded ?? 0 }} friends rewarded so far</p>
</template>
```

`useReferrals()` returns `code`, `link`, `shareText`, `program` (what each side gets), `referrals` (counts of `claimed`, `held` and `rewarded`, with each referral's state), `sharePages` and `setSharePages(share)`, `copy()`, `share()`, `canShare`, `copied`, `isLoading`, `isPending` and `error`. The code is made on the first read in the browser, for a signed-in person. A referral reads as a state and a time, never who the friend is.

## Claim a referral

A referral is claimed in an explicit step. The page a link opens (`/r/:code`, `pages.referral`) says who invited the visitor, by first name, and what they get. "Sign up to claim" sends them to sign in and back to the same page with `?claim=1`, where the claim runs once; someone who is signed in already claims with a button. The claim runs on its own only after a sign-in from the last ten minutes (`claimReferral({ code, fromSignIn: true })`), so a link carrying `?claim=1` that someone signed in earlier opens shows them the button instead. The code travels in the address, like a [campaign link](https://nuxt-backend.dev/docs/build/growth/offers/campaign-links). Nothing is stored on the visitor's device.

While the app is not public, signing up there needs a [ticket](https://nuxt-backend.dev/docs/build/growth/launch#what-admits-a-new-address) first, so the page says so instead of offering a sign-up that only joins the waitlist: it links the invite page, carrying the code so the sign-in it leads to comes back here, where the person claims with the button; the waitlist, in early access; and a sign-in for an account made less than a day ago, which can still claim (an older one is past attribution). A friend a [member's ticket](https://nuxt-backend.dev/docs/build/growth/launch/invites#let-members-bring-friends) admits needs no page: with `memberTickets({ referrals })`, the friend is the member's referral as their account is made.

A page of your own at the same path builds on `useReferralInvite()`, the page's logic without its markup. It reads the link on the server too, so the offer is in the first paint:

```vue [app/pages/r/[code].vue]
<script setup lang="ts">
const { state, preview, signInTo, claim, error } = useReferralInvite()
</script>

<template>
  <p v-if="state === 'invalid'">This link no longer works.</p>
  <template v-else-if="preview">
    <p>{{ preview.inviter ?? 'A friend' }} invited you.</p>
    <NuxtLink v-if="state === 'ready' && signInTo" :to="signInTo">Sign up to claim</NuxtLink>
    <button v-else-if="state === 'claimable'" @click="claim()">Claim</button>
    <p v-else-if="state === 'claimed'">It's yours.</p>
    <p v-else-if="state === 'own'">This is your own link.</p>
    <p v-else-if="state === 'ignored'">{{ error?.message ?? 'This offer can\'t be used on your account.' }}</p>
  </template>
</template>
```

`useReferralInvite()` returns `code`, from the page's `code` param; `state`, one of `checking`, `invalid`, `ready`, `claimable`, `claiming`, `claimed`, `ignored` and `own`; `preview`; `signInTo`, the sign-in that returns here with `?claim=1`; `inviteTo`, the invite page carrying the code (`/invite?ref=<code>`) for a visitor who holds an invite while the app is closed; `closed`, `true` while the app is not public, so a visitor needs a ticket before signing up, and `undefined` while the phase loads, so offer neither the sign-up nor the ways to a ticket until it is read (a phase still unread after five seconds reads as `false`, as one that could not be read, so a connection that never opens leaves nobody without a way in); `claim()`; `isLoading`, `isPending` and `error`. It runs the claim on `?claim=1` for you. The server renders nobody as signed in, so a signed-in reader sees `ready` until the browser takes over, and a link that can't be read reads as `invalid`, with the reason in `error`.

An invalid, expired or own code is ignored and never blocks a sign-up: `claimReferral` answers `{ claimed: false, reason }` instead of an error. The first referral claimed wins, and an account older than a day is past attribution (`too_late`): a referral is for a new account.

Your server code claims one with `referrals.claimFor(ctx, { referrerId, userId })`, in a mutation or an action, under the same checks and answers; it makes the referrer's code if they have none. A [member's ticket](https://nuxt-backend.dev/docs/build/growth/launch/invites#let-members-bring-friends) with `memberTickets({ referrals })` claims its friends this way.

## Reward after the hold

Only the referred person's own first paid order counts, on the billing entity they pay for. It starts the hold, and a refund during the hold voids the referral. When the hold ends, the package checks the order again, applies the caps, and grants the rewards:

- **The person referred** already had theirs at checkout: the server applied the discount by id, locked so a typed code can't replace it, or opened the checkout with the trial days.
- **The referrer's credits** arrive as the pack, claimed at no cost the way a [gift](https://nuxt-backend.dev/docs/build/growth/offers/gifts#how-a-gift-works) is: a single-use, code-free discount and a $0 order the provider fulfils.
- **The referrer's free months**: on a paid plan, the provider moves their renewal date later by the months. On the free plan, they get a [plan pass](https://nuxt-backend.dev/docs/build/growth/offers/plan-passes) for the months. A workspace on a pass already (a gift, a reverse trial, an earlier reward) gets them once that pass ends: they are never stacked on it, nor lost.

A moved renewal date skips the plan's credit grants for the free months, since the provider grants a plan's credits when a cycle starts. Where credits are the plan's value, reward the referrer with a pack instead.

The referrer is told in the app: `referral.rewarded` derives an in-app notification once [notifications](https://nuxt-backend.dev/docs/build/email/notifications) are on. Both steps are on the activity trail as `referral.claimed` and `referral.rewarded` ([Events](https://nuxt-backend.dev/docs/reference/backend/events#backend-events)).

## Close the share loop

Every strip a Panels author shares by link is a small ad for the app. A public [share page](https://nuxt-backend.dev/docs/build/data/files/share-links) shows the strip, a "Made with Panels" badge and the owner's referral code, so a reader who signs up from it claims the referral like one from `/r/<code>`:

- **The badge links to /r/<code>**, the owner's referral link, with the visitor's claim step on the page it opens. `referrals.codeFor(ctx, userId)` gives the share page the code.
- **It discloses the incentive.** The badge's title reads "Made with Panels. The author earns credits when you join." Endorsement rules ask the sharer's gain to be visible where the link is.
- **The owner chooses.** `codeFor` answers `null` unless the owner has a code and has not turned it off for their share pages (`setSharePages(false)`, on `<ReferralCard>`); the badge stays without it.
- **The same caps hold.** A share page earns no reward past `caps`, and a share page opened by its owner never counts: a person's own code is ignored.

The badge is markup of your share page, so you restyle or replace it like the rest of the page.

## Abuse checks

- **Self-referral is refused**: the same account, the same address once plus tags and dots are taken out, or a first payment on a billing entity the referrer belongs to (the same customer paying), which voids the referral.
- **Suspicious referrals are flagged**, not refused: one network and browser for both sides (the sessions each has opened), and a burst on one code (five claims in an hour). An administrator releases or voids a flagged reward in the admin console. A flag first found at the payment sends the referral back to the queue, released before or not.
- **A mailbox is referred once.** An account erased and made again with the same address claims no code: the referral that brought it stays with its referrer, holding only a digest of the mailbox. An erasure never hands a referrer back a slot under the caps for a reward already granted.
- **A reward is reversible** until its hold ends. A personal code is never a provider discount code, so it can't leak to coupon sites.

## In the admin console

The admin console gets a Referrals tab once `backend/referrals.ts` exists: the whole program's totals by state, the program's hold and caps, the top referrers, the flagged queue and each referrer's history. The totals and each referrer's count are kept as every referral changes state, so they cover every claim however many there are. Releasing or voiding a flagged reward is an administrator's write, so it asks for a [recent sign-in](https://nuxt-backend.dev/docs/build/auth/access/step-up).

## What happens when…

- **A code is invalid, expired or the visitor's own:** it is ignored, and the sign-up goes on without a referral. It never blocks anyone.
- **A second code arrives later:** the first referral claimed wins.
- **The first order is refunded during the hold:** the referral is voided, and nobody gets a reward.
- **A referrer reaches perReferrer, or the program reaches perMonth:** the referral is recorded and counted, with no reward. `useReferrals()` shows it as `claimed`.
- **The checks flag a referral:** its reward waits for an administrator to release or void it, in the flagged queue however old the claim.
- **A reward can't be granted** (the provider is down, say): it is tried again an hour later, behind the referrals due before it, so it never holds up the rest.
- **An administrator releases a flag without a recent sign-in:** it is refused as [`reauthentication_required`](https://nuxt-backend.dev/docs/reference/backend/errors#reauthentication_required).

## Limits

- **Never cash.** Rewards are catalog products and discounts, granted through Polar.
- **At least a 14-day hold**, the EU withdrawal period, so a reward always waits that long.
- **Free months skip plan credits** on a paid plan, since the renewal date moves and no cycle starts.
- **No emails to strangers.** People share their own link; the app never mails someone without an account.
- **No card comparison.** The provider does not share card details, so matching cards are not a flag.
- **One billing entity per person.** A reward lands on the referrer's own billing entity (their personal workspace, or the account with `billTo: 'user'`). An app's own `resolveEntity` hides it from the program, so `setupReferrals` refuses a `referrer` reward with one: grant that reward in your own code then.

## Test it

Claim a referral end to end on Polar's sandbox: open `/r/<code>` signed out, sign up with a fresh address from the dev inbox, and pay with the test card `4242 4242 4242 4242`. With `hold` set to 14 days, the referral reads as `held`. In a backend test, a person's own code is ignored:

```ts [backend/referrals.test.ts]
import { asUser, defineBackendTestApp } from 'nuxt-backend/test'
import { expect, test } from 'vitest'
import { api } from './_generated/api'
import schema from './schema'

const testApp = defineBackendTestApp(schema, import.meta.glob('./**/*.ts'))

test('claiming your own code records nothing', async () => {
  const ada = await asUser(testApp(), { email: 'ada@panels.example' })
  const { code } = await ada.mutation(api.referrals.getReferralCode, {})
  await ada.mutation(api.referrals.claimReferral, { code })
  expect(await ada.query(api.referrals.getReferrals, {})).toMatchObject({ claimed: 0 })
})
```

## Related

- [Polar](https://nuxt-backend.dev/docs/services/polar): the account that grants the rewards.
- [Run a promotion](https://nuxt-backend.dev/docs/build/growth/offers): the codeless discount a referred person gets.
- [Gift a plan as a pass](https://nuxt-backend.dev/docs/build/growth/offers/plan-passes): free months for a referrer on the free plan.
- [Share by link](https://nuxt-backend.dev/docs/build/data/files/share-links): the public pages that carry the badge and the code.
- [Guardrails on growth features](https://nuxt-backend.dev/docs/start/concepts/principles#guardrails-on-growth-features): disclosure, consent and the claim step.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
