Create a custom referral program for free using Firebase

The alternative to spending hundreds of dollars using third-party software


11 min read

Create a custom referral program for free using Firebase


Having a great referral program in place is a smart marketing move however, third-party referral software such as Growsurf have really high price tags that may not be a good option for startups. In this comprehensive guide, we'll walk you through the process of building a powerful referral program using Firebase in your vanilla project. Whether you're a fintech enthusiast, a startup founder, or a developer eager to enhance user engagement, this guide is for you.

Explore the key elements and steps involved in creating a robust referral program that can be seamlessly integrated into your web or mobile application. From understanding the impact of referral programs to deploying Firebase Cloud Functions for real-time reward calculations, we've got you covered.

The code snippets provided are adaptable to various applications, ensuring flexibility and scalability. Let's dive right in!

A more simple version for non technical founders can be found at the bottom of this blog.

File Structure:

  1. index.html: The main HTML file where the user dashboard is displayed.

  2. style.css: The main CSS file for styling.

  3. app.js: The main JavaScript file for your application logic.

  4. firebase-config.js: A separate file to handle Firebase configuration.

  5. auth.js: A file to manage user authentication.

  6. referral.js: A file to handle referral-related logic.

1. Understanding Referral Programs

Why Referral Programs Matter:

Referral programs serve as potent tools across industries, driving user growth and enhancing conversion rates. The ability to leverage existing users to bring in new customers is a game-changer.

Referral programs can significantly impact user acquisition and conversion rates. Harnessing the trust between existing and potential users leads to more organic and engaged customer bases.

2. Tools of the Trade

Introduction to Firebase:

Firebase offers a suite of tools that cater to various application needs. From real-time databases to authentication services, it provides a robust foundation for building dynamic web or mobile applications.

// Initializing Firebase in your project
const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "",
    projectId: "your-project-id",
    storageBucket: "",
    messagingSenderId: "your-messaging-sender-id",
    appId: "your-app-id",

// Initialize Firebase

Benefits of a Vanilla Build Approach:

A vanilla build approach, devoid of extensive frameworks, provides greater control over your codebase. It optimizes performance and allows for a modular architecture.

3. Designing Your Referral Object in Firestore

Creating a Firestore Collection for Referrals:

Firestore, as Firebase's NoSQL database, facilitates the creation of a collection to store essential information about referrals.

// Creating a Firestore collection for referrals
const db = firebase.firestore();
const referralsCollection = db.collection('referrals');

Defining the Referral Data Structure:

Defining the structure of referral data ensures effective data management within Firestore.

// Defining the structure of the referral data in Firestore
const referralData = {
    referrerId: 'user123',
    referredId: 'user456',
    status: 'pending',
    reward: 0,
    createdAt: firebase.firestore.FieldValue.serverTimestamp(),

4. Generating Unique Referral Codes with JavaScript

Crafting a Function for Generating Unique Codes:

A JavaScript function can be crafted to generate unique referral codes, adding a personalized touch to your program.

// JavaScript function to generate unique referral codes
const generateReferralCode = () => {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let referralCode = '';
    for (let i = 0; i < 8; i++) {
        referralCode += characters.charAt(Math.floor(Math.random() * characters.length));
    return referralCode;

Integrating Code Generation into Your Platform:

Integrate the referral code generation function seamlessly into your application to make it a seamless part of the user experience.

// Integrating referral code generation into your platform
const userReferralCode = generateReferralCode();
console.log(`Your referral code is: ${userReferralCode}`);

Craft a function to generate referral links, providing users with an effortless way to share your application.

// JavaScript function to generate referral links
const generateReferralLink = (userId, referralCode) => {
    return `${referralCode}`;

Seamlessly integrate referral links into your application's user interface for a user-friendly experience.

<!-- HTML code to display the referral link in the user interface -->
<a href="${generateReferralLink(, userReferralCode)}">Share your referral link</a>

6. Tracking Referrals on Sign-Up

Implementing Referral Tracking in User Sign-Up Logic:

Integrate referral tracking logic into the user sign-up process to associate every new user with their referrer.

// JavaScript code to implement referral tracking on user sign-up
const trackReferral = (referrerId, referredId) => {
    if (referrerId !== referredId) {
            status: 'pending',
            reward: 0,
            createdAt: firebase.firestore.FieldValue.serverTimestamp(),

Ensuring Valid Referrals and Preventing Self-Referrals:

Implement measures to validate referrals and prevent users from referring themselves.

// Code to ensure valid referrals and prevent self-referrals
const isValidReferral = (referrerId, referredId) => {
    return referrerId !== referredId;

7. Calculating and Distributing Rewards with Firebase Cloud Functions

Utilizing Firebase Cloud Functions for Real-Time Reward Calculation:

Leverage Firebase Cloud Functions for real-time reward calculation to enhance the responsiveness of your referral program.

// Firebase Cloud Function for reward calculation
exports.calculateReward = functions.firestore
    .onCreate((snapshot, context) => {
        const referralId = context.params.referralId;
        // Implement your reward calculation logic here
        const rewardAmount = calculateRewardAmount(referralId);
        // Update referral record with the reward amount
        return snapshot.ref.update({ reward: rewardAmount });

Deploying and Monitoring Cloud Functions for Reliability:

Deploy and monitor Cloud Functions to ensure the reliability of your real-time reward calculation.

# Command to deploy Cloud

 Functions using Firebase CLI
firebase deploy --only functions

8. Enhancing Security Measures

Implementing Fraud Prevention Measures with Firebase:

Security is paramount. Implement measures to prevent fraudulent activities within your referral program.

// Firebase Authentication for user identity verification
const isAuthenticated = () => {
    // Implement your authentication logic using Firebase Authentication
    return true; // Placeholder, replace with actual authentication check

// Additional code for IP and device tracking
// Implement as per your security requirements

Ensuring the Integrity of Your Referral Program:

Maintain the integrity of your referral program by implementing additional security measures.

// Regular audit code for referral data integrity
const auditReferralData = () => {
    // Implement regular audits to identify and rectify any anomalies
    console.log("Audit complete. Referral data is secure.");

// Code to educate users on program integrity
const educateUsers = () => {
    console.log("Educate users on the importance of maintaining program integrity for a fair ecosystem.");

9. User Interface Integration

Seamlessly Integrating the Referral Program:

Ensure a cohesive and engaging user experience by seamlessly integrating the referral program into your application.

<!-- HTML code to display the referral dashboard in the user interface -->
    <h3>Your Referral Dashboard</h3>
    <p>Your Referral Count: ${getUserReferralCount(}</p>
    <a href="${generateReferralLink(, userReferralCode)}">Share your referral link</a>

Creating an Intuitive Experience for Users:

Make it intuitive for users to share and track their referrals.

// JavaScript code to display real-time referral data
const displayRealTimeData = () => {
    // Use Firebase Realtime Database or Firestore to display up-to-date referral information
    console.log("Displaying real-time referral data in the user interface.");

// JavaScript code to provide sharing options
const provideSharingOptions = () => {
    console.log("Integrate social sharing options for users to share their referral links easily.");

10. Monitoring, Analytics, and Optimization

Implementing Logging and Analytics:

Gather valuable insights into the performance of your referral program through effective logging and analytics.

// Firebase Analytics initialization code
const initAnalytics = () => {;

// Custom logging code for specific events and user activities
const logEvents = () => {
    console.log("Logging events for performance monitoring and analysis.");

Optimizing the Referral Program:

Continuously optimize your referral program based on user behavior and insights gained through analytics.

// JavaScript code to analyze user behavior
const analyzeUserBehavior = () => {
    console.log("Regularly analyze user interactions with the referral program.");

// JavaScript code to iterate and improve the program
const iterateAndImprove = () => {
    console.log("Implement improvements based on user feedback and program performance data.");

Simplified Program Using HTML, CSS, & Javascript

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Fintech Startup</title>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;

        .dashboard {
            border: 1px solid #ddd;
            padding: 20px;
            margin-bottom: 20px;

        .referral-link {
            margin-top: 10px;

        .signup-form {
            max-width: 400px;
            margin: 0 auto;

    <div class="dashboard">
        <h2>Your Account Dashboard</h2>
        <p>Welcome, Vashon Gonzales!</p>

        <!-- Step 3: Display Referral Code -->
        <p>Your referral code is: <strong id="referralCode"></strong></p>

        <!-- Step 4: Referral Link -->
        <p class="referral-link">Share this referral link: <a id="referralLink" href="#"></a></p>

    <!-- Step 5: Track Referrals -->
    <div class="signup-form">
        <h2>Sign Up</h2>
        <form action="signup.php" method="post">
            <!-- Add other form fields as needed -->

            <!-- Add a hidden input for the referral code -->
            <input type="hidden" name="referralCode" id="signupReferralCode">

            <button type="submit">Sign Up</button>

        // JavaScript for generating and displaying referral code and link
        function generateReferralCode() {
            const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            let code = '';

            for (let i = 0; i < 8; i++) {
                code += characters.charAt(Math.floor(Math.random() * characters.length));

            return code;

        // Set user's referral code and link on page load
        document.getElementById('referralCode').innerText = generateReferralCode();
        document.getElementById('referralLink').href = `${document.getElementById('referralCode').innerText}`;

        // Set the referral code in the signup form
        document.getElementById('signupReferralCode').value = document.getElementById('referralCode').innerText;


This template includes a basic account dashboard, a referral code display, and a referral link for sharing. The signup form has a hidden input field to capture the referral code.

Adapt the form action (signup.php) to your backend processing script if needed.

signup.php would typically be a server-side script (written in PHP in this case) that processes the user's signup information and handles the referral logic. Here's a simplified example of what signup.php might look like:


// Check if the form is submitted

    // Retrieve other form fields as needed
    $username = $_POST["username"];
    $email = $_POST["email"];

    // Retrieve the referral code
    $referralCode = $_POST["referralCode"];

    // Perform user registration logic, store user data in the database, etc.
    // ...

    // Check if a referral code is present
    if (!empty($referralCode)) {
        // Perform actions for a referral signup
        // Update the referrer's account in the database, provide rewards, etc.
        // ...

        // Notify both the referrer and the new user about the successful referral
        $referrerNotification = "Congratulations! Someone signed up using your referral code.";
        $newUserNotification = "You successfully signed up using a referral code!";

        // Example: Send notifications (replace with your actual notification mechanism)
        mail($referrerEmail, "Referral Success", $referrerNotification);
        mail($newUserEmail, "Referral Success", $newUserNotification);

    // Redirect the user to a thank you page or their account dashboard
    header("Location: thank-you.php");

// If the form is not submitted, redirect the user to the homepage or another appropriate page
header("Location: index.php");

This PHP script does the following:

  1. Retrieves form data (like username, email, and referral code) submitted via POST.

  2. Performs user registration logic (store data in the database, etc.).

  3. Checks if a referral code is present. If yes, it performs actions for a referral signup, such as updating the referrer's account and notifying both the referrer and the new user.

  4. Redirects the user to a thank you page or their account dashboard.

For Node users:

Since you're using a Node.js backend, you'll need to handle the signup logic within your Node.js application. Here's a general guide on how to integrate the referral logic into your Node.js backend:

  1. File Structure:

    • If you don't have one already, create a directory for your server-side code. Place your Node.js files in this directory.
  2. Create a New File:

    • Create a new file, let's call it signup.js or any appropriate name for your signup logic. Paste the Node.js code into this file.
  3. Update Form Action:

    • In your HTML signup form, ensure that the action attribute points to the correct endpoint in your Node.js server. For example:

        <form action="/signup" method="post">
  4. Express.js Setup:

    • If you're using Express.js for your Node.js server, you'll need to set up route handling for the signup endpoint. Here's a basic example:

        const express = require('express');
        const bodyParser = require('body-parser');
        const app = express();
        app.use(bodyParser.urlencoded({ extended: true }));
     '/signup', (req, res) => {
            // Handle signup logic here
            // ...
            // Redirect the user to a thank you page or their account dashboard
        // Start the server
        const PORT = process.env.PORT || 3000;
        app.listen(PORT, () => {
            console.log(`Server is running on port ${PORT}`);
  5. Database Integration:

    • Integrate the user registration logic with your database. Connect to the database, insert user data, and update the referrer's account. If you're using a specific database library or ORM (Object-Relational Mapping), adjust the code accordingly.
  6. Notifications:

    • If you're using email notifications or any other form of notification, ensure that the notification mechanisms are properly configured and working within your Node.js application.
  7. Security Considerations:

    • Ensure that your Node.js code is secure. Use parameterized queries or an ORM to prevent SQL injection, validate and sanitize user input, and implement other security best practices.
  8. Testing:

    • Test the integration by submitting the signup form. Check if the form data is being processed correctly, and if the referral logic is working as expected.
  9. Deployment:

    • Deploy the updated Node.js files to your server.
Make sure you already have Node.js packages using npm install if you're using external libraries like Express.js or others.

Did you find this article valuable?

Support Paygeon Core Articles by becoming a sponsor. Any amount is appreciated!