DEV Community

Michael Burrows
Michael Burrows

Posted on • Originally published at w3collective.com

Build a web page hit counter with JavaScript & Firebase

Whilst not commonly used on modern websites hit counters can still be a useful way to provide social proof of a websites popularity. Building this JavaScript hit counter also serves as a nice introduction to Firebase if you’ve never worked with the platform before.

To get started you’l need a Firebase account which you can create for free. Once logged into your account goto the Firebase Console and add a new project called “Hit Counter”. On step 2 of the project setup you can disable the Google Analytics as it isn’t required in this instance.

Once setup is complete you’ll then be taken to a screen which has the option to add Firebase to your app, select the “Web” option and follow the prompts:

Alt Text

To complete the setup we need to add a database which is done by selecting “Realtime Database” from the sidebar menu. When prompted for the security rules select “Start in test mode”.

With Firebase setup create a new HTML file with the following markup:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Hit Counter</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div id="hit-counter"></div>
    <script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.2.1/firebase-database.js"></script>
    <script src="script.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

This provides a <div> for us to render the number of hits and loads the required Firebase SDKs. We’ll put the hit counter functionality in the script.js file so go ahead and create that now.

First up in the script.js file we need to add the Firebase config which can be found under “Project Settings” in the console, it will look something like the following:

const firebaseConfig = {
  apiKey: "AIzaSyDNvZTWK5frqUpF43TLLKcCY-18K3dat7g",
  authDomain: "hit-counter-bef28.firebaseapp.com",
  projectId: "hit-counter-bef28",
  storageBucket: "hit-counter-bef28.appspot.com",
  messagingSenderId: "732467417978",
  appId: "1:732467417978:web:acd0103f6d42a48bdd3cc3"
};
firebase.initializeApp(firebaseConfig);
Enter fullscreen mode Exit fullscreen mode

Next we’ll a define a hitCounter variable and hide the hit counter until the data is loaded:

const hitCounter = document.getElementById("hit-counter");
hitCounter.style.display = "none";
Enter fullscreen mode Exit fullscreen mode

To get the current number of total hits we first define the location in the database we want to query (totalHits). Then the Firebase DataSnapshot is used to retrieve a snapshot of the data, a snapshot is simply a picture of the data at a single point in time:

const db = firebase.database().ref("totalHits");
db.on("value", (snapshot) => {
  hitCounter.textContent = snapshot.val();  
});
Enter fullscreen mode Exit fullscreen mode

To update the hit counter total we use the Firebase Transaction which retrieves the totalHits from the database before increasing by +1 and saving the updated value:

db.transaction(
  (totalHits) => totalHits + 1,
  (error) => {
    if (error) {
      console.log(error);
    } else {
      hitCounter.style.display = "inline-block";
    }
  }
);
Enter fullscreen mode Exit fullscreen mode

At this stage the hit counter is fully functioning and will update every time you refresh the page. However you may only want to update the total hits once per user and not each time the page is viewed. To achieve this we’ll need to set a cookie and only update the totalHits if the cookie doesn’t exist.

I’ve written about cookies in a previous article and was able to re-use that code here. By moving the transaction inside the checkUserCookie function the hits will now only update if the cookie isn’t found:

const userCookieName = "returningVisitor";
checkUserCookie(userCookieName);

function checkUserCookie(userCookieName) {
  const regEx = new RegExp(userCookieName, "g");
  const cookieExists = document.cookie.match(regEx);
  if (cookieExists != null) {
    hitCounter.style.display = "block";
  } else {
    createUserCookie(userCookieName);
    db.transaction(
      (totalHits) => totalHits + 1,
      (error) => {
        if (error) {
          console.log(error);
        } else {
          hitCounter.style.display = "inline-block";
        }
      }
    );
  }
}

function createUserCookie(userCookieName) {
  const userCookieValue = "Yes";
  const userCookieDays = 7;
  let expiryDate = new Date();
  expiryDate.setDate(expiryDate.getDate() + userCookieDays);
  document.cookie =
    userCookieName +
    "=" +
    userCookieValue +
    "; expires=" +
    expiryDate.toGMTString() +
    "path=/";
}
Enter fullscreen mode Exit fullscreen mode

Note – cookies aren’t saved in Google Chrome when the file is viewed on the local file system (file:///). You’ll need to either put the file on a server or use another browser like Firefox or Safari to test locally.

Finally for the old school look create a style.css file with the following CSS:

#hit-counter {
  font-family: serif;
  font-size: 15px;
  background-color: #000;
  color: greenyellow;  
  padding: 3px 6px;     
}
Enter fullscreen mode Exit fullscreen mode

That concludes this tutorial, you should now have a fully functioning JavaScript web page hit counter that can easily be dropped into any website. Thanks for reading 🙂

Top comments (1)

Collapse
 
ayush01arya profile image
Ayush01arya

Nice