Referral Links System on Website

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1289
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1198
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    903
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1129
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    861
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    881

Referral System with Referral Links

Referral system incentivizes users to attract new customers. Mechanics: unique link → registration → attribution → reward. Details in business logic: discount, account credit, percentage of payment.

Data Schema

model ReferralCode {
  id        String   @id @default(cuid())
  code      String   @unique  // unique code: "JOHN2024"
  userId    String   @unique  // one code per user
  createdAt DateTime @default(now())

  user      User       @relation(fields: [userId], references: [id])
  referrals Referral[]
}

model Referral {
  id            String         @id @default(cuid())
  referralCodeId String
  referredUserId String        @unique  // user can be referred once
  status        ReferralStatus @default(PENDING)
  rewardAmount  Int?           // in kopeks/cents
  rewardPaidAt  DateTime?
  createdAt     DateTime       @default(now())

  referralCode ReferralCode @relation(fields: [referralCodeId], references: [id])
  referredUser User         @relation(fields: [referredUserId], references: [id])
}

enum ReferralStatus {
  PENDING    // registered but not paid
  QUALIFIED  // met condition (first payment)
  REWARDED   // reward paid
  CANCELLED  // cancelled (refund etc)
}

Code Generation and URL Building

// lib/referral.ts
import { customAlphabet } from 'nanoid';

const generateCode = customAlphabet('ABCDEFGHJKLMNPQRSTUVWXYZ23456789', 8);

export async function getOrCreateReferralCode(userId: string): Promise<string> {
  const existing = await db.referralCode.findUnique({
    where: { userId }
  });

  if (existing) return existing.code;

  // Try to create unique code
  for (let attempt = 0; attempt < 5; attempt++) {
    const code = generateCode();
    try {
      const created = await db.referralCode.create({
        data: { userId, code }
      });
      return created.code;
    } catch (e) {
      // Uniqueness violated — try again
    }
  }

  throw new Error('Failed to generate unique referral code');
}

export function buildReferralUrl(code: string, baseUrl?: string): string {
  const base = baseUrl ?? process.env.APP_URL!;
  return `${base}/?ref=${code}`;
}

Referral Tracking on Registration

// Middleware: save ref in cookie
// middleware.ts
export function middleware(request: NextRequest) {
  const response = NextResponse.next();
  const ref = request.nextUrl.searchParams.get('ref');

  if (ref && !request.cookies.get('referral_code')) {
    // Cookie lives 30 days — even if user doesn't register immediately
    response.cookies.set('referral_code', ref, {
      maxAge: 60 * 60 * 24 * 30,
      httpOnly: true,
      sameSite: 'lax',
    });
  }

  return response;
}
// On new user registration
export async function registerUser(email: string, password: string, referralCode?: string) {
  const user = await createUser(email, password);

  if (referralCode) {
    const code = await db.referralCode.findUnique({
      where: { code: referralCode },
    });

    if (code && code.userId !== user.id) { // can't refer self
      await db.referral.create({
        data: {
          referralCodeId: code.id,
          referredUserId: user.id,
          status: 'PENDING',
        }
      });
    }
  }

  return user;
}

Reward Accrual

// On first successful payment (webhook from Stripe)
export async function handleFirstPayment(userId: string, paymentAmount: number) {
  const referral = await db.referral.findFirst({
    where: {
      referredUserId: userId,
      status: 'PENDING',
    },
    include: { referralCode: true }
  });

  if (!referral) return;

  // Reward: 20% of first payment
  const rewardAmount = Math.floor(paymentAmount * 0.20);

  await db.$transaction([
    db.referral.update({
      where: { id: referral.id },
      data: {
        status: 'QUALIFIED',
        rewardAmount,
      }
    }),
    // Accrue credit to referrer
    db.userBalance.upsert({
      where: { userId: referral.referralCode.userId },
      create: {
        userId: referral.referralCode.userId,
        balance: rewardAmount,
      },
      update: {
        balance: { increment: rewardAmount }
      }
    }),
  ]);

  // Notify referrer
  await sendReferralRewardEmail({
    userId: referral.referralCode.userId,
    amount: rewardAmount,
  });
}

Referral Dashboard

// app/dashboard/referrals/page.tsx
export default async function ReferralsPage() {
  const session = await auth();
  const code = await getOrCreateReferralCode(session!.user.id);
  const referralUrl = buildReferralUrl(code);

  const stats = await db.referral.groupBy({
    by: ['status'],
    where: { referralCode: { userId: session!.user.id } },
    _count: true,
    _sum: { rewardAmount: true },
  });

  return (
    <div>
      <h1>Referral Program</h1>
      <ReferralLinkCopy url={referralUrl} code={code} />
      <ReferralStats stats={stats} />
      <ReferralHistory userId={session!.user.id} />
    </div>
  );
}

Referral system development with tracking, attribution and reward accrual — 3–5 business days.