Skip to main content

Bug Fix: Automatic Referral Code Generation for New Registered Users

Last Updated: 16/07/2026
Type: Bug Fix & Backend System Spec β€” Referral System
System: Backend User Registration Service (POST /api/register / User creation hook)
Severity: πŸ”΄ High β€” Blocks the referral/marketing program since users cannot share their invite codes

Feedback Screenshot:


1. The Issue​

In the CMS customer list view, the Referral Code column is empty for all recently registered users (both Registered and Verified statuses).

Every user signing up for the Golden Membership program must be assigned a unique personal referral code immediately upon account creation. This code is required for the "Invite & Earn" (Giα»›i thiệu bαΊ‘n bΓ¨) program.


2. Solution Specifications​

2.1 Trigger Timing​

The referral code generation must be triggered automatically on the backend during the user registration process.

  • Hook: Before saving the user entity to the database (e.g. beforeCreate ORM hook or inside the registration service controller).
  • Fallback script: A migration script must be executed to generate unique codes for existing users who currently have a null referralCode field.

2.2 Referral Code Generation Rule​

The code must be:

  1. Unique: Case-insensitive unique constraint in the database.
  2. Short & Readable: Uppercase alphanumeric characters (no confusing symbols like 0 vs O, or 1 vs I).
  3. Format Options:
  • Combine the first letters of the user's name (or a standard prefix like GL) followed by 6 random alphanumeric characters.
  • Example: GLXXXXXX (e.g. GLA3B9C5)

Option B (Simple Base36 String)​

  • A 6-8 character unique hash generated from the user's ID or database auto-increment index.
  • Example: 8F9C3A

3. Code Implementation Spec (Backend)​

3.1 Code Generation Helper​

import crypto from 'crypto';

/**
* Generates a unique, readable 8-character referral code
* Format: GL + 6 alphanumeric characters (excluding O, 0, I, 1)
*/
export const generateUniqueReferralCode = (): string => {
const allowedChars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // Excluded: 0, O, 1, I
let code = 'GL';

// Generate 6 random characters
for (let i = 0; i < 6; i++) {
const randomIndex = crypto.randomInt(0, allowedChars.length);
code += allowedChars[randomIndex];
}

return code;
};

3.2 Registration Service Hook (Node.js/Prisma Example)​

// Inside user registration service controller

export const registerUser = async (req: Request, res: Response) => {
const { phone, password, fullName } = req.body;

// 1. Generate unique referral code
let referralCode = generateUniqueReferralCode();

// 2. Collision check (extremely rare, but safe for production)
let isUnique = false;
let attempts = 0;
while (!isUnique && attempts < 5) {
const existingUser = await prisma.user.findUnique({
where: { referralCode }
});
if (!existingUser) {
isUnique = true;
} else {
referralCode = generateUniqueReferralCode();
attempts++;
}
}

// 3. Create user record
const newUser = await prisma.user.create({
data: {
phone,
passwordHash,
fullName,
referralCode, // βœ… Saved automatically
pointsBalance: 10000, // Welcome bonus point
}
});

return res.status(201).json(newUser);
};

4. Database Migration script (For Existing Null Records)​

A database migration/one-time script must run to populate null referral codes in the production database:

-- PostgreSQL / MySQL safe generator concept (run via backend script to ensure uniqueness)
-- Pseudo-code script:
-- 1. Fetch all users WHERE referral_code IS NULL.
-- 2. Loop and update each user with a generated referral code.
-- 3. Alter table constraints: ALTER TABLE users MODIFY referral_code VARCHAR(20) NOT NULL UNIQUE;

Technical Checklist​

  • Add a UNIQUE constraint to the referralCode (or referral_code) field in the user database schema.
  • Implement the generateUniqueReferralCode helper in the backend utility package.
  • Add the code generation and collision check logic to the user registration controller/services (POST /api/register and OAuth hooks).
  • Write a script to retroactively assign unique referral codes to all existing accounts currently displaying empty/null values.
  • Test case:
    • Register a new user profile via the mobile app.
    • Query database or open the CMS customers list β†’ verify the user record contains a valid, generated referral code starting with "GL" (e.g. GL7K3P9B).
  • Ensure that referral codes are case-insensitive when queried during friend referrals.