Creating a Leaderboard for Your Website Game Using Firebase and JavaScript

Tajammal Maqbool
4 min readFeb 23, 2024

--

Leaderboards are a vital tool in the realm of online gaming since they encourage player engagement and rivalry. Include a leaderboard to improve user experience and motivate players to compete for the top rank, regardless of the complexity of your multiplayer game or basic browser-based game.

We’ll look at how to use Firebase and JavaScript to make a leaderboard for your online game in this blog.

Leaderboard using Firebase and Javascript
Leaderboard

What is Firebase?

Google offers a feature-rich platform called Firebase for creating mobile and online applications. It provides many services, including as hosting, authentication, real-time databases, and more. Since Firebase’s real-time database enables real-time data synchronization among clients, it is very helpful for creating features like leaderboards.

Firebase — WHAT IS FIREBASE?
Firebase

Setting Up Firebase:

Before we begin, you’ll need to set up a Firebase project. Head over to the Firebase console (console.firebase.google.com), create a new project, and follow the instructions to set it up. Once your project is created, you’ll need to enable Firebase Firestore Database.

Firebase — Create Firebase Project Step 01
Create Firebase Project — Firebase

Firebase Firestore:

Open the Firebase Firestore and create new database by selecting the server area and then create it in test or production mode as you want. Read more here:

Create Database — Firebase Firestore Database
Create Database — Firestore Database

After creating this database, we need to change the rules of it, so we can enable the write operations on the database. Go in to ‘Rules’ tabs. Change this “allow read, write: if false;” to “allow read, write: if true;” and publish the change.

Make write to true — Firebase Firestore Database
Make write to true — Firebase Firestore Database

Now go to your project home page and create new app connection by clicking on the web. Then enter any name that you want and Register the app.

Register the app — Firebase Firestore Database
Register the app — Firebase Firestore Database

Good news!!! You have done the setup of firebase, we are ready to use it. Go to your node and install firebase by running this command:

npm install firebase

You can use the firebase library to make connection with your cloud project and do the all operations like read, write, update and delete etc. Here is code for making a leaderboard with unquie username for your game. Add your config values to make connection with your project. Check it,

import { initializeApp } from "firebase/app";
import { addDoc, collection, getDocs, getFirestore, limit, orderBy, query, updateDoc, where } from "firebase/firestore";


const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};

const app = initializeApp(firebaseConfig);

const IsUsernameExist = async (username) => {
const db = getFirestore(app);
const querySnapshot = await getDocs(query(collection(db, "leaderboard"), where("username", "==", username)));
return querySnapshot.size > 0;
}

const AddUserInLeaderboard = async (username, score) => {
const db = getFirestore(app);

try {
const isUsernameExist = await IsUsernameExist(username);
if (isUsernameExist) {
const querySnapshot = await getDocs(query(collection(db, "leaderboard"), where("username", "==", username)));
querySnapshot.forEach((doc) => {
updateDoc(doc.ref, { score: score });
});
return true;
}
const docRef = await addDoc(collection(db, "leaderboard"), {
username: username,
score: score
});
return true;
} catch (e) {
console.error("Error adding document: ", e);
}

return false;
}

const GetLeaderboard = async () => {
const db = getFirestore(app);
const querySnapshot = await getDocs(query(collection(db, "leaderboard"), orderBy("score", "desc"), limit(10)));
let leaderboard = [];
querySnapshot.forEach((doc) => {
leaderboard.push(doc.data());
});
return leaderboard;
}

export { AddUserInLeaderboard, GetLeaderboard, IsUsernameExist };

Cool, Now you can import these functions inside any file where you want to use it.

We can also able to see the all data in our firebase cloud project. For that you need to go on the Firestore Database, select the collection with name “leaderboard” and then we can select any document to see.

Collections and Documents to see — Firebase Firestore Database
Collections and Documents to see — Firebase Firestore Database

Game Development Blogs:

Conclusion

Congratulations! You’ve successfully created a leaderboard for your website game using Firebase and JavaScript. By leveraging Firebase’s real-time database, you’ve built a dynamic leaderboard that updates in real time as players compete and achieve high scores. Feel free to customize the design and functionality to suit your game’s requirements, and watch as your players engage with the leaderboard to climb the ranks and claim the top spot.

--

--

Tajammal Maqbool

I have been a Website & Game Developer since 2020. I graduated in Computer Science from UET Lahore. Passionate about sharing my programming knowledge!!!!