$ xyruscodev7

Blog

Preventing False Counts

If you read my last post about adding a view counter, good for you. Now you can see your page views updated in real-time, but the counts are being updated with every refresh.

·4 min read
CookiesNext.jsTutorial

If you read my last post about adding a view counter, good for you. Now you can see your page views updated in real-time, but the counts are being updated with every refresh. Didn't notice it yet? Okay, hit refresh. See it now? Great. We can fix this easily using Cookies.

The Problem

Every time a user loads the page, the view count increments. That means refreshing the page 10 times = 10 views counted, even though it's the same person.

The Solution

We can use cookies to check if a page has already been visited by the current user:

import Cookies from 'js-cookie';

useEffect(() => {
  const viewedKey = `viewed_${slug}`;

  if (!Cookies.get(viewedKey)) {
    const registerView = () =>
      fetch(`/api/views/${slug}`, {
        method: 'POST'
      });

    registerView();
    Cookies.set(viewedKey, '1', { expires: 1 });
  }
}, [slug]);

The cookie expires after 1 day, so repeat visits after that will count again. Adjust the expiration as needed.

Conclusion

Simple fix, big impact. Cookies prevent inflation of your view counts and give you more accurate analytics.

Comments