A few months ago, I wrote an article about adding a comments section to your Astro blog using Giscus, and I was thrilled to see how many people found it helpful. Following that success, I decided to share another useful feature that can enhance your blog: a views counter for your articles.
Adding a views counter to your blog posts is a great way to track engagement and show your readers how popular your articles are. In this guide, I’ll show you how to implement a beautiful and animated views counter for your Astro blog using a free hit counter service.
Table of Content
🎯 The Solution
The solution is very simple and dosnt require any server side code or API keys. We’ll use hits.seeyoufarm.com, a free and reliable hit counter service that doesn’t require any authentication or API keys. The service provides a simple URL-based API that returns an SVG badge with the view count. We’ll extract the count from this badge and display it with a smooth animation.
👀 Page Views Component
Without any further ado, here is the code for the PageViews
component, you only need to add this to your blog post layout and pass the current page URL to it.
Let’s break down and explain the code.
The component is very simple, it accepts a url
prop that will be used to track views for specific pages. We create a simple eye icon for the visual appeal of the counter and we use a three dots loading animation to make it more appealing.
In the script section, we have a function called updateViewCount
that handles fetching and displaying the view count. Here’s how it works:
- It first fetches the SVG content from the hit counter service using the
fetchWithProxy
function to handle CORS - Since the service returns an SVG containing the view count, we use a regular expression to extract the numeric value
- The regex pattern
/<text[^>]*fill="#fff"[^>]*>([\d\s/]+)<\/text>/
matches text elements in the SVG and captures the view count - Once we have the count, we initialize the display at 0 and animate up to the actual value
- If there are any errors in fetching or parsing, we gracefully fall back to showing “N/A”
Once we have the view count, we use the animateNumber
function to create a smooth animation effect. This function animates the counter from 0 to the actual view count over a 1 second duration. Under the hood, it leverages the browser’s requestAnimationFrame
API to create a fluid easing animation with optimal performance. The easing effect makes the counting animation feel more polished and natural compared to an instant update or linear transition.
📝 Using the Page Views Component in Your Blog
To add the views counter to your blog posts, import and use the PageViews
component in your blog post layout:
✨ The Result
Go to the top of the page and you’ll see the page views counter for this page.
Make sure to try it out on your blog and let me know what you think in the comments below! 🎉