Custom incremental UserID Generation

Custom Code

Hello All,

I know that fire base creates a UUID for each document created but they are random, I want to create a custom incremental UserID whenever a new user has signed up, I have tried creating an document where i can just increment a field and generate a Id based on the counter Value,

But the proble with this method is it involves a read operation(current count value) a write( increment to the count) and then creating a id and writing it in the document, that is 3 operations for one Id, it would become expensive as the app scales up

then I tried creating a custom cloud function which would be called at the moment of user sign up the cloud function will return the user id(string), code mentioned below

now will the Counter value increment with each call or will it just start from one again(does it create multiple instances in the time of concurrency) , and does the value ever get reset if the function is not invoked for a long time

this might be silly question but for a someone with no coding background reading the firebase documentation doesn't workπŸ˜…

and as a First-time developer i'm scared because of the 3 operations as i somehow got 92k reads with no users at all😬

What have you tried so far?
const functions = require('firebase-functions');
const admin = require('firebase-admin');

// Initialize Firebase Admin SDK
admin.initializeApp();

// Counter to keep track of user IDs
let counter = 1;

exports.newCloudFunction = functions.https.onCall(async (data, context) => {
  if (!context.auth.uid) {
    return;
  }

  // Get the current year (24 for 2024)
  const currentYear = new Date().getFullYear() % 100;

  // Generate the numeric part (padded with zeros)
  const numericPart = String(counter).padStart(4, '0'); // e.g., 0001, 0002, ...

  // Generate the syllables (aa, ab, ac, ..., zz)
  const syllables = String.fromCharCode(97 + Math.floor(counter / 26)) + String.fromCharCode(97 + (counter % 26));

  // Construct the user ID
  const userId = Bhag${currentYear}${syllables}${numericPart};

  // Increment the counter for the next call
  counter++;

  return userId;
});

Did you check FlutterFlow's Documentation for this topic?
No
2
4 replies