We’ll use a Firebase Cloud Function to generate a random username every time a new user registers via Firebase Authentication.
This function generates a username every time a new user registers and inserts it into the users collection in the "username" field.
You can rename collection and field if you want
Here's what the username will look like:
It starts with
user-
.Includes a mix of lowercase letters and numbers.
Is verified to be unique before being assigned.
Here’s the complete Firebase Cloud Function to handle username generation:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const db = admin.firestore();
exports.assignRandomUsername = functions
.region('insert-your-database-region')
.auth.user()
.onCreate(async (user) => {
const uid = user.uid;
try {
// Generate a random username
let username = generateUsername();
// Ensure it's unique
username = await ensureUniqueUsername(username);
// Save the username to Firestore
await db.collection('users').doc(uid).set(
{ username },
{ merge: true }
);
console.log(`Username assigned: ${username}`);
} catch (error) {
console.error(`Error assigning username: ${error}`);
}
});
function generateUsername() {
const prefix = "user-";
const randomPart = Math.random().toString(36).substring(2, 12); // 10 random characters
return prefix + randomPart;
}
async function ensureUniqueUsername(username) {
while (true) {
const snapshot = await db
.collection('users')
.where('username', '==', username)
.limit(1)
.get();
if (snapshot.empty) {
return username; // It's unique!
}
// Generate a new username if it's already taken
username = generateUsername();
}
}
This solution can generate up to 3,656 quadrillions of combinations to avoid looping.
What do you think? Have you found better solutions?
It can also be useful for generating unique codes for items or shipments