So after publishing my last post, I noticed that I couldn't query the Hashnode API for the number of views for an individual post and this was kinda getting to me. My site runs on Next.js and is deployed to Vercel. I had Vercel Analytics on so I could see the views per page but I couldn't get that into the UI.
After looking everywhere I couldn't get it to work then I remembered I also use Firebase. So here's how I used Firebase Firestore to track views on my blog posts.
Setting Up Firebase
First things first, you'll need a Firebase Project. Head over to Firebase and create one.
Then you'll need to create a Firestore Database. It's in the Build section. You'll want to start in test mode.
Then you'll add a collection and add a document to it as well.
The View Counter Component
Here's the React component that tracks and displays views:
import { useEffect } from 'react';
import useSWR from 'swr';
import fetcher from 'lib/fetcher';
import { View } from 'lib/types';
const ViewCounter = ({ slug, isCard }) => {
const { data } = useSWR<View>(`/api/views/${slug}`, fetcher);
const views = new Number(data?.total);
useEffect(() => {
if (!isCard) {
const registerView = () =>
fetch(`/api/views/${slug}`, {
method: 'POST'
});
registerView();
}
}, [isCard, slug]);
return <span>{`${data?.total?.toLocaleString() || '---'} views`}</span>;
};
export default ViewCounter;
Conclusion
And that's it! You now have a view counter on your blog. It updates in real-time and uses Firebase Firestore as the backend.