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.
Prerequisites
- 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
Add referral fields to the user schema and generate codes on signup
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.
1// Cloud Function: generateReferralCode on user creation2const functions = require('firebase-functions');3const admin = require('firebase-admin');4const crypto = require('crypto');5admin.initializeApp();67exports.generateReferralCode = functions.auth.user().onCreate(async (user) => {8 const db = admin.firestore();9 let code;10 let isUnique = false;11 while (!isUnique) {12 code = crypto.randomBytes(4).toString('hex').toUpperCase();13 const existing = await db.collection('users')14 .where('referralCode', '==', code).limit(1).get();15 isUnique = existing.empty;16 }17 await db.collection('users').doc(user.uid).update({ referralCode: code, referralCount: 0 });18});Expected result: Every new user automatically receives a unique 8-character referral code stored on their user document.
Add the referral code input to the signup flow
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.
Validate and process referrals in a Cloud Function
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.
1// Cloud Function: processReferral2exports.processReferral = functions.https.onCall(async (data, context) => {3 if (!context.auth) throw new functions.https.HttpsError('unauthenticated', 'Login required');4 const { referralCode } = data;5 if (!referralCode) return { success: false, reason: 'No code provided' };6 const uid = context.auth.uid;7 const db = admin.firestore();89 const referrerSnap = await db.collection('users')10 .where('referralCode', '==', referralCode).limit(1).get();11 if (referrerSnap.empty) {12 throw new functions.https.HttpsError('not-found', 'Invalid referral code');13 }14 const referrerDoc = referrerSnap.docs[0];15 if (referrerDoc.id === uid) {16 throw new functions.https.HttpsError('failed-precondition', 'Cannot refer yourself');17 }18 const newUserDoc = await db.collection('users').doc(uid).get();19 if (newUserDoc.data().referredBy) {20 throw new functions.https.HttpsError('already-exists', 'Already referred');21 }2223 const batch = db.batch();24 // Update new user25 batch.update(db.collection('users').doc(uid), {26 referredBy: referralCode,27 signupDiscount: 0.10, // 10% first order discount28 });29 // Reward referrer30 batch.update(referrerDoc.ref, {31 referralCount: admin.firestore.FieldValue.increment(1),32 rewardPoints: admin.firestore.FieldValue.increment(500),33 });34 // Log event35 batch.create(db.collection('referral_events').doc(), {36 referrerId: referrerDoc.id,37 refereeId: uid,38 referralCode: referralCode,39 referrerReward: '500 points',40 refereeReward: '10% discount',41 timestamp: admin.firestore.FieldValue.serverTimestamp(),42 });43 await batch.commit();44 return { success: true };45});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.
Build the referral sharing page with code display and share button
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.
Build the referral dashboard with history and earnings
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 working example
1// Cloud Functions: Referral Rewards System2const functions = require('firebase-functions');3const admin = require('firebase-admin');4const crypto = require('crypto');5admin.initializeApp();67// Generate unique referral code on signup8exports.generateReferralCode = functions.auth.user().onCreate(async (user) => {9 const db = admin.firestore();10 let code;11 let isUnique = false;12 while (!isUnique) {13 code = crypto.randomBytes(4).toString('hex').toUpperCase();14 const existing = await db.collection('users')15 .where('referralCode', '==', code).limit(1).get();16 isUnique = existing.empty;17 }18 await db.collection('users').doc(user.uid).set({19 referralCode: code,20 referralCount: 0,21 referredBy: null,22 rewardPoints: 0,23 }, { merge: true });24});2526// Process referral code during signup27exports.processReferral = functions.https.onCall(async (data, context) => {28 if (!context.auth) throw new functions.https.HttpsError('unauthenticated', 'Login required');29 const { referralCode } = data;30 if (!referralCode) return { success: false };31 const uid = context.auth.uid;32 const db = admin.firestore();3334 // Find referrer35 const referrerSnap = await db.collection('users')36 .where('referralCode', '==', referralCode).limit(1).get();37 if (referrerSnap.empty)38 throw new functions.https.HttpsError('not-found', 'Invalid code');3940 const referrerDoc = referrerSnap.docs[0];41 if (referrerDoc.id === uid)42 throw new functions.https.HttpsError('failed-precondition', 'Cannot refer yourself');4344 const newUser = await db.collection('users').doc(uid).get();45 if (newUser.data()?.referredBy)46 throw new functions.https.HttpsError('already-exists', 'Already referred');4748 const batch = db.batch();49 batch.update(db.collection('users').doc(uid), {50 referredBy: referralCode,51 signupDiscount: 0.10,52 });53 batch.update(referrerDoc.ref, {54 referralCount: admin.firestore.FieldValue.increment(1),55 rewardPoints: admin.firestore.FieldValue.increment(500),56 });57 batch.create(db.collection('referral_events').doc(), {58 referrerId: referrerDoc.id,59 refereeId: uid,60 referralCode,61 referrerReward: '500 points',62 refereeReward: '10% discount',63 timestamp: admin.firestore.FieldValue.serverTimestamp(),64 });65 await batch.commit();66 return { success: true, referrerName: referrerDoc.data().displayName };67});Common mistakes when creating a Referral Rewards System in FlutterFlow
Why it's a problem: Allowing self-referral by not checking if referrer UID equals referee UID
How to avoid: 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.
Why it's a problem: Validating the referral code on the client instead of the server
How to avoid: Perform all referral validation and reward distribution in a Cloud Function. The client only sends the code; the server handles everything else.
Why it's a problem: Not logging referral events in a separate collection
How to avoid: 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
Still stuck?
Copy one of these prompts to get a personalized, step-by-step explanation.
I need to build a referral rewards system in FlutterFlow. Show me the Cloud Function that generates unique referral codes on user signup, the validation function that processes codes during registration with self-referral prevention, and the Firestore schema for tracking referrals and bilateral rewards.
Create a referral page showing the user's unique referral code with a copy button and share button. Below, add a ListView of successful referrals from a referral_events collection. Add an optional referral code TextField on the signup page.
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.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation