# How to Create a Referral Rewards System in FlutterFlow

- Tool: FlutterFlow
- Difficulty: Beginner
- Time required: 20-25 min
- Compatibility: FlutterFlow Free+
- Last updated: March 2026

## TL;DR

Build a referral system by generating a unique 8-character referral code for each user on signup, storing it on their user document alongside a referralCount tracker. New users enter a referral code during registration. A Cloud Function validates the code, links referrer to referee, and awards both parties: the referrer gets points or a free month, and the referee gets a discount. A referral_events collection logs every successful referral, and a dashboard shows users their referral history and total earnings.

## Building a Referral Rewards System in FlutterFlow

Referral programs are one of the most cost-effective growth strategies. This tutorial builds a complete system where each user gets a unique referral code, can share it via native share sheet, and both parties receive rewards when a new user signs up with the code. The Cloud Function handles validation, fraud prevention, and reward distribution securely.

## Before you start

- A FlutterFlow project with Firebase Authentication enabled
- Firestore database set up in your Firebase project
- Basic understanding of Cloud Functions and FlutterFlow Action Flows
- The share_plus package for native sharing (optional)

## Step-by-step guide

### 1. Add referral fields to the user schema and generate codes on signup

Add three fields to the users collection: referralCode (String, unique 8-character alphanumeric), referredBy (String, the code used during signup, nullable), and referralCount (Integer, default 0). Create a Cloud Function triggered on user creation (auth.user().onCreate) that generates a unique 8-character code using a combination of the UID and random bytes, then updates the user document with the generated referralCode. Use a while loop to check for uniqueness by querying existing codes before writing.

```
// Cloud Function: generateReferralCode on user creation
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const crypto = require('crypto');
admin.initializeApp();

exports.generateReferralCode = functions.auth.user().onCreate(async (user) => {
  const db = admin.firestore();
  let code;
  let isUnique = false;
  while (!isUnique) {
    code = crypto.randomBytes(4).toString('hex').toUpperCase();
    const existing = await db.collection('users')
      .where('referralCode', '==', code).limit(1).get();
    isUnique = existing.empty;
  }
  await db.collection('users').doc(user.uid).update({ referralCode: code, referralCount: 0 });
});
```

**Expected result:** Every new user automatically receives a unique 8-character referral code stored on their user document.

### 2. Add the referral code input to the signup flow

On your signup page, add an optional TextField labeled 'Have a referral code?' below the password field. Style it with a smaller font and a collapsible Section or Expandable so it does not clutter the main signup form. Store the entered code in Page State referralCodeInput. After successful Firebase Authentication signup, pass the referralCodeInput to a Cloud Function called processReferral along with the new user's UID. If the field is empty, skip the referral processing entirely.

**Expected result:** The signup page has an optional referral code field. The entered code is passed to a Cloud Function after successful account creation.

### 3. Validate and process referrals in a Cloud Function

Create a Cloud Function called processReferral that receives referralCode and newUserId. The function validates: (1) the code exists by querying users where referralCode matches, (2) the referrer's UID is not the same as newUserId (preventing self-referral), (3) the new user has not already been referred (referredBy is null). If all checks pass, update the new user's referredBy field with the code, increment the referrer's referralCount, award the referrer (e.g., 500 points via FieldValue.increment on rewardPoints), apply the referee benefit (e.g., set a discount flag), and create a referral_events document logging the event.

```
// Cloud Function: processReferral
exports.processReferral = functions.https.onCall(async (data, context) => {
  if (!context.auth) throw new functions.https.HttpsError('unauthenticated', 'Login required');
  const { referralCode } = data;
  if (!referralCode) return { success: false, reason: 'No code provided' };
  const uid = context.auth.uid;
  const db = admin.firestore();

  const referrerSnap = await db.collection('users')
    .where('referralCode', '==', referralCode).limit(1).get();
  if (referrerSnap.empty) {
    throw new functions.https.HttpsError('not-found', 'Invalid referral code');
  }
  const referrerDoc = referrerSnap.docs[0];
  if (referrerDoc.id === uid) {
    throw new functions.https.HttpsError('failed-precondition', 'Cannot refer yourself');
  }
  const newUserDoc = await db.collection('users').doc(uid).get();
  if (newUserDoc.data().referredBy) {
    throw new functions.https.HttpsError('already-exists', 'Already referred');
  }

  const batch = db.batch();
  // Update new user
  batch.update(db.collection('users').doc(uid), {
    referredBy: referralCode,
    signupDiscount: 0.10, // 10% first order discount
  });
  // Reward referrer
  batch.update(referrerDoc.ref, {
    referralCount: admin.firestore.FieldValue.increment(1),
    rewardPoints: admin.firestore.FieldValue.increment(500),
  });
  // Log event
  batch.create(db.collection('referral_events').doc(), {
    referrerId: referrerDoc.id,
    refereeId: uid,
    referralCode: referralCode,
    referrerReward: '500 points',
    refereeReward: '10% discount',
    timestamp: admin.firestore.FieldValue.serverTimestamp(),
  });
  await batch.commit();
  return { success: true };
});
```

**Expected result:** Valid referral codes link the new user to their referrer, award both parties, and log the event. Self-referral and duplicate referrals are blocked.

### 4. Build the referral sharing page with code display and share button

Create a ReferralPage accessible from the user's profile or settings. Display the user's referral code in a large, copyable Text widget with a Copy IconButton that copies the code to the clipboard via a Copy to Clipboard action. Below, add a Share Button that uses a Custom Action with the share_plus package to open the native share sheet with a message like 'Join {AppName} and get 10% off your first order! Use my code: {referralCode}. Download here: {appLink}'. Also display the referralCount and a summary of rewards earned from referrals.

**Expected result:** Users see their referral code, can copy it or share it via the native share sheet, and see their referral stats.

### 5. Build the referral dashboard with history and earnings

Below the share section on the ReferralPage, add a ListView with a Backend Query on referral_events where referrerId equals the current user, ordered by timestamp descending. Each list item shows the referee's display name (or 'New User'), the date, and the reward earned. At the top of the list, add summary cards: Total Referrals (referralCount), Total Points Earned (referralCount * 500), and Active Referral Code. Use Conditional Visibility to show a motivational message like 'Share your code to earn 500 points per referral!' when referralCount is 0.

**Expected result:** The referral dashboard shows a history of successful referrals with dates and rewards, plus summary statistics of total earnings.

## Complete code example

File: `referral_system_functions.js`

```dart
// Cloud Functions: Referral Rewards System
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const crypto = require('crypto');
admin.initializeApp();

// Generate unique referral code on signup
exports.generateReferralCode = functions.auth.user().onCreate(async (user) => {
  const db = admin.firestore();
  let code;
  let isUnique = false;
  while (!isUnique) {
    code = crypto.randomBytes(4).toString('hex').toUpperCase();
    const existing = await db.collection('users')
      .where('referralCode', '==', code).limit(1).get();
    isUnique = existing.empty;
  }
  await db.collection('users').doc(user.uid).set({
    referralCode: code,
    referralCount: 0,
    referredBy: null,
    rewardPoints: 0,
  }, { merge: true });
});

// Process referral code during signup
exports.processReferral = functions.https.onCall(async (data, context) => {
  if (!context.auth) throw new functions.https.HttpsError('unauthenticated', 'Login required');
  const { referralCode } = data;
  if (!referralCode) return { success: false };
  const uid = context.auth.uid;
  const db = admin.firestore();

  // Find referrer
  const referrerSnap = await db.collection('users')
    .where('referralCode', '==', referralCode).limit(1).get();
  if (referrerSnap.empty)
    throw new functions.https.HttpsError('not-found', 'Invalid code');

  const referrerDoc = referrerSnap.docs[0];
  if (referrerDoc.id === uid)
    throw new functions.https.HttpsError('failed-precondition', 'Cannot refer yourself');

  const newUser = await db.collection('users').doc(uid).get();
  if (newUser.data()?.referredBy)
    throw new functions.https.HttpsError('already-exists', 'Already referred');

  const batch = db.batch();
  batch.update(db.collection('users').doc(uid), {
    referredBy: referralCode,
    signupDiscount: 0.10,
  });
  batch.update(referrerDoc.ref, {
    referralCount: admin.firestore.FieldValue.increment(1),
    rewardPoints: admin.firestore.FieldValue.increment(500),
  });
  batch.create(db.collection('referral_events').doc(), {
    referrerId: referrerDoc.id,
    refereeId: uid,
    referralCode,
    referrerReward: '500 points',
    refereeReward: '10% discount',
    timestamp: admin.firestore.FieldValue.serverTimestamp(),
  });
  await batch.commit();
  return { success: true, referrerName: referrerDoc.data().displayName };
});
```

## Common mistakes

- **Allowing self-referral by not checking if referrer UID equals referee UID** — Users create a second account using their own referral code to earn free rewards. This costs the business money without gaining a real new user. Fix: In the Cloud Function, verify that the referrer's UID does not equal the new user's UID. Optionally check device fingerprint or IP for additional fraud prevention.
- **Validating the referral code on the client instead of the server** — Client-side validation can be bypassed, allowing users to submit invalid codes or manipulate rewards. Fix: Perform all referral validation and reward distribution in a Cloud Function. The client only sends the code; the server handles everything else.
- **Not logging referral events in a separate collection** — Without a referral_events log, you cannot audit referral patterns, detect fraud rings, or calculate marketing ROI. Fix: Create a referral_events document for every successful referral with referrer ID, referee ID, timestamp, and rewards granted.

## Best practices

- Generate referral codes in Cloud Functions using cryptographic randomness, not user-guessable patterns
- Make the referral code field optional during signup to minimize registration friction
- Award both referrer and referee to create a win-win incentive structure
- Use the native share sheet via share_plus for maximum sharing flexibility across apps
- Display the referral code prominently and add a one-tap copy button for convenience
- Set a cap on maximum referral rewards per user to limit abuse potential
- Track referral conversion rates to measure the program's effectiveness

## Frequently asked questions

### Can I offer different rewards for different referral milestones?

Yes. Check the referrer's referralCount after incrementing. At milestones (5, 10, 25 referrals), award bonus rewards. Store milestone thresholds in Firestore so admins can adjust them.

### How do I share a referral link instead of a code?

Use Firebase Dynamic Links or a URL shortener to create a link like yourapp.com/signup?ref=CODE. On the signup page, read the ref parameter from the URL and auto-fill the referral code field.

### Can I require the referee to make a purchase before the referrer gets rewarded?

Yes. Instead of awarding on signup, create the referral_event with status pending. A Cloud Function triggered on the referee's first order updates the status to completed and awards the referrer.

### How do I detect referral fraud rings?

Monitor referral_events for patterns: same IP addresses, similar email domains, rapid successive signups, or accounts that sign up and never engage. Flag suspicious patterns for manual review.

### Can I limit referral rewards to a maximum per month?

Yes. In the processReferral function, query referral_events for the referrer within the current month. If the count exceeds your monthly cap, skip the reward and inform the referrer their monthly limit has been reached.

### Can RapidDev help build a viral referral program?

Yes. RapidDev can design and implement referral systems with deep link sharing, multi-tier rewards, fraud detection, A/B testing of incentive structures, and analytics dashboards to track growth impact.

---

Source: https://www.rapidevelopers.com/flutterflow-tutorials/how-to-create-a-referral-rewards-system-in-flutterflow
© RapidDev — https://www.rapidevelopers.com/flutterflow-tutorials/how-to-create-a-referral-rewards-system-in-flutterflow
