Launch Waitlist KitLaunch Waitlist KitPre-launch waitlist app with referral queue boosts, admin CMS, email capture, CSV export, webhooks, and an embeddable signup form—built on Next.js 16 and Prisma.$24

Your waitlist API andstatus pageonly work if thePrisma waitlist modelencodes referrals correctly. AreferralCodeunique on every row, areferredBylink to the inviter, and aunique emailare the minimum contract for viral pre-launch signups in Next.js. Get the schema wrong and you chase bugs in queue math, duplicate signups, and broken?ref=attribution.

This guide is the schema deep dive behindreferral queue position. OneWaitlistEntrymodel, self-relations, optionaldouble opt-incolumns, migrations, indexes, seed data, and integrity rules you enforce in the signup route.


What the schema must support

Capability Field / relation One person, one rowemail@uniqueShare linksreferralCode@uniqueWho invited whomreferredById+ self-relation Fair queue orderbasePositionset once at insert Verified referralsconfirmedAt(optional opt-in) AuditcreatedAt, optional consent timestamp

The signup handler and status page read these fields. They do not re-derive referral trees from logs.

Prerequisites

  • Prisma 5+ with PostgreSQL (recommended for production waitlists).

  • Basic migrations workflow (prisma migrate dev).

  • Familiarity with the App Router signup route from article 01.


Step 1: Production-readyWaitlistEntrymodel

Start from the core model and add opt-in fields you need:

model WaitlistEntry {
  id                 String    @id @default(cuid())
  email              String    @unique
  referralCode       String    @unique
  referredById       String?
  basePosition       Int
  confirmationToken  String?   @unique
  confirmationSentAt DateTime?
  confirmedAt        DateTime?
  consentAt          DateTime?
  createdAt          DateTime  @default(now())
  updatedAt          DateTime  @updatedAt

  referredBy WaitlistEntry?  @relation("WaitlistReferrals", fields: [referredById], references: [id], onDelete: SetNull)
  referrals  WaitlistEntry[] @relation("WaitlistReferrals")

  @@index([referredById])
  @@index([confirmedAt])
  @@index([basePosition])
}

Naming:use an explicit relation name (WaitlistReferrals) so future models do not collide with other self-relations.

onDelete: SetNull:if you delete a row in admin, referred users keep their signup but lose attribution. Alternative: forbid delete while referrals exist.

consentAt:optional timestamp when the user checked the consent box. Helpful for compliance exports; not required for v1.

Runnpx prisma migrate dev --name waitlist_referral_schema.


Step 2: WhyreferralCodeandreferredByare separate

Concept Storage Public share codereferralCode(in URLs as?ref=) Internal parent linkreferredById(FK to inviter'sid)

Never put internalidin share URLs. Never store onlyreferralCodeon the child without resolving toreferredByIdat signup.

Signup resolution (pseudo):

let referredById: string | undefined;
if (ref) {
  const referrer = await db.waitlistEntry.findUnique({
    where: { referralCode: ref },
  });
  if (referrer && referrer.email !== email) {
    referredById = referrer.id;
  }
}

Block self-referral by comparing normalized email, not by schema constraint alone.


Step 3: Unique email and normalization

Prisma enforces uniqueness on the stored string. If users sign up asYou@Mail.comandyou@mail.com, Postgres treats them as different unless you normalize.

App rule:email.trim().toLowerCase()on every write and lookup.

Database option (Postgres):citextextension:

email String @unique @db.Citext

RequiresCREATE EXTENSION citextin a migration. Many teams stick to lowercase in application code only.

Duplicate signup should return the existingreferralCode, not throw on unique violation (see article 01).


Step 4:basePositionwithout renumbering

basePositionis the join order at insert time. Referral boosts are computed on read (article 01), not by updating every row's position.

const basePosition = (await db.waitlistEntry.count()) + 1;

Race at launch:two concurrent signups can read the same count. For high concurrency, use a transaction with serializable isolation or a dedicated sequence table. At early-stage volume, count + 1 in a transaction is usually enough:

await db.$transaction(async (tx) => {
  const count = await tx.waitlistEntry.count();
  return tx.waitlistEntry.create({
    data: {
      email,
      referralCode,
      referredById,
      basePosition: count + 1,
      consentAt: new Date(),
    },
  });
});

Do not use auto-increment onidas public position;cuidids are not human order.


Step 5: Double opt-in columns (optional)

Ifdouble opt-inis enabled:

  • confirmationTokenunique until confirm

  • confirmedAtset on confirm; clear token

  • Count referrals withconfirmedAt IS NOT NULLonly

Migration from v1 without opt-in:

-- Example: add nullable columns without backfill
ALTER TABLE "WaitlistEntry" ADD COLUMN "confirmationToken" TEXT;
ALTER TABLE "WaitlistEntry" ADD COLUMN "confirmedAt" TIMESTAMP;

Backfill existing rows:UPDATE "WaitlistEntry" SET "confirmedAt" = "createdAt" WHERE "confirmedAt" IS NULLif you want legacy users treated as confirmed.


Step 6: Indexes and query patterns

Query Index Signup by email@uniqueonemailResolve?ref=@uniqueonreferralCodeCount referrals per user@@index([referredById])Admin filter pending@@index([confirmedAt])

await db.waitlistEntry.count({
  where: {
    referredById: entryId,
    confirmedAt: { not: null },
  },
});

WithoutreferredByIdindex, referral counts slow down as the list grows.


Step 7: Referral code generation and collisions

import { randomBytes } from "crypto";

function generateReferralCode(): string {
  return randomBytes(4).toString("hex");
}

async function createWithUniqueCode(data: Omit<...>) {
  for (let attempt = 0; attempt < 5; attempt++) {
    const referralCode = generateReferralCode();
    try {
      return await db.waitlistEntry.create({ data: { ...data, referralCode } });
    } catch (e) {
      if (isUniqueViolation(e, "referralCode")) continue;
      throw e;
    }
  }
  throw new Error("Could not allocate referral code");
}

Eight hex characters are fine under ~10k signups. Increase length if you see collisions in logs.


Step 8: Seed script for local dev

prisma/seed.ts:

import { PrismaClient } from "@prisma/client";

const db = new PrismaClient();

async function main() {
  await db.waitlistEntry.deleteMany();

  const alice = await db.waitlistEntry.create({
    data: {
      email: "alice@example.com",
      referralCode: "aaaa1111",
      basePosition: 1,
      confirmedAt: new Date(),
      consentAt: new Date(),
    },
  });

  await db.waitlistEntry.create({
    data: {
      email: "bob@example.com",
      referralCode: "bbbb2222",
      basePosition: 2,
      referredById: alice.id,
      confirmedAt: new Date(),
      consentAt: new Date(),
    },
  });
}

main()
  .then(() => db.$disconnect())
  .catch(async (e) => {
    console.error(e);
    await db.$disconnect();
    process.exit(1);
  });

Wire inpackage.json:"prisma": { "seed": "tsx prisma/seed.ts" }. Teststatus pagewith?code=aaaa1111.


Step 9: How schema ties to API and status routes

Route Schema touchpointsPOST /api/waitlist/signupcreate row, unique email, setreferredByIdGET /api/waitlist/confirmsetconfirmedAt, clear token/status?code=lookup byreferralCode, read referrals relation

Embed route (Week 6) posts the same payload shape.Honeypotruns before Prisma writes.


Step 10: Admin and CSV export shape

Admin dashboards (Week 9 in this series) usually list: email,referralCode,basePosition,confirmedAt,referredById,createdAt. Your schema should expose enough to export CSV without joins to mystery tables.

const rows = await db.waitlistEntry.findMany({
  orderBy: { basePosition: "asc" },
  select: {
    email: true,
    referralCode: true,
    basePosition: true,
    confirmedAt: true,
    createdAt: true,
    referredBy: { select: { email: true, referralCode: true } },
  },
});

Keep PII columns out of public APIs. Status page usesreferralCodeonly, not email of referrers.


Step 11: Evolution without breaking live waitlists

Adding columns in production:

  1. Add nullable columns in a migration.

  2. Deploy code that reads new fields optionally.

  3. Backfill if needed (confirmedAtfor legacy users).

  4. Add NOT NULL constraints only after backfill completes.

RenamingreferralCodeon a live list breaks share links in inboxes. Prefer additive changes.

If you change boost rules in application code, you rarely need schema changes. That is whybasePositionstays immutable while effective position is computed on read in article 01.


Step 12: WaitlistEntry vs a generic Lead model

Lead CRM Referral waitlist Sales stages, ownersbasePosition+ referral graph Duplicate leads OK Unique email No public share codereferralCodein URLs

Do not overloadLeadwith waitlist concerns unless your product truly merges both. A dedicatedWaitlistEntrykeeps migrations predictable for launch kits.

Referral depth:the schema stores one parent per signup (referredById). Multi-level MLM-style trees are the same table; depth walks are rare for waitlist UX. Product copy usually rewards direct invites only, which matches a single FK.

Timezone fields:storeDateTimein UTC in Postgres (timestamptz). Prisma defaults are UTC-aware when configured; display local time only in the UI.


Step 13: Test checklist

  1. Migrate on empty DB; seed runs clean.

  2. Two signups: uniquereferralCode, sequentialbasePosition.

  3. Signup with valid?ref=: child'sreferredByIdpoints to parent.

  4. Duplicate email: no second row.

  5. Invalidref: signup succeeds,referredByIdnull.

  6. Opt-in off:confirmedAtset at insert; counts include referrals.

  7. Prisma Studio: relation graph looks correct.

  8. Export query returns referrer email for referred rows without N+1 (useselect+ relation).

Prisma Studio:openWaitlistEntry, expandreferralson a seeded parent, confirm child rows point back viareferredBy.


Common failures

Unique constraint on email throws 500

Fix:catch duplicate in signup route; return existingreferralCode.

Referrals do not link

Cause:storingreferralCodeinreferredByIdby mistake.Fix:FK is inviterid, resolved from code at signup.

Position gaps inbasePosition

Cause:rolled-back failed inserts or manual deletes.Fix:gaps are OK; order is monotonic, not dense.

Slow referral counts

Fix:add@@index([referredById]); filterconfirmedAtconsistently with product rules.

Case-sensitive duplicate emails

Fix:normalize to lowercase in application code (or citext).

Nullable referredById with invalid ref from client

Fix:resolve ref server-side; ignore unknown codes; never trust hiddenrefwithout lookup.

Huge referral trees

Fix:indexreferredById; avoid recursive SQL for position; count direct referrals only unless product rules say otherwise.

Schema work is unglamorous but it prevents production referrals from silently failing. Invest an afternoon in indexes and seeds before you announce the waitlist publicly.


Schema ships with the kit

Migrations, referral relations, opt-in fields, and admin-ready models are tedious to reinvent before every launch.

Launch Waitlist KitfromSkryptixincludes:

  • Prisma waitlist schema withreferralCode,referredBy, and unique email

  • Signup, status, referrals, and optional double opt-in

  • Admin signups, CSV export, webhooks, and embed form

Migrations and seed for waitlist schema are included in Launch Waitlist Kit.

Get Launch Waitlist Kit →

Launch Waitlist KitLaunch Waitlist KitPre-launch waitlist app with referral queue boosts, admin CMS, email capture, CSV export, webhooks, and an embeddable signup form—built on Next.js 16 and Prisma.$24

FAQ

What fields should a Prisma waitlist model include for referrals?

At minimum: uniqueemail, uniquereferralCode, optionalreferredByIdself-relation,basePosition, and timestamps. AddconfirmedAtandconfirmationTokenif you use double opt-in.

What is the difference between referralCode and referredById?

referralCodeis the public token in?ref=links.referredByIdis the internal foreign key to the inviter's row, set after you resolve a valid ref at signup.

Should email be unique in the waitlist table?

Yes. One row per address. Handle duplicates in the API by returning the existing user's status code instead of creating a second row.

Can I use UUID instead of cuid for id?

Yes. Public identifiers should still bereferralCode, notid. Cuid and UUID are both fine for internal primary keys.

How does the schema support embed and webhooks later?

Embed signups use the sameWaitlistEntrycreate path. Webhooks fire after insert or afterconfirmedAtis set; no extra tables required beyond optionalWebhookDeliveryif you build retries in-house (most teams POST once from the signup handler).

How do I model referredBy in Prisma?

Use a self-relation onWaitlistEntry:referredByIdoptional FK toid, plusreferralsas the reverse list of signups attributed to that entry.

Do I need indexes beyond unique constraints?

An index onreferredByIdspeeds referral counts. An index onconfirmedAthelps admin filters when double opt-in is on.


Written by the team behind Skryptix. We build Launch Waitlist Kit so founders can focus on the launch, not waitlist infrastructure.