DEV Community

Ryan Chou
Ryan Chou

Posted on

Introducing React Page Tracker: Simplify Navigation Tracking

Preface

I recently encountered a requirement to implement a "back to the previous page" button.

Since my project uses Next.js, the straightforward solution was to call router.back(). Problem solved, right?

But here’s the catch: if the user lands on the page with the back button for the first time, clicking it would ideally navigate them back to the homepage instead of leaving the site altogether!


It seemed easy at first...

Initially, I thought simply tracking whether the user navigated between pages using pathname would suffice.

Turns out, if the user keeps clicking links to go deeper and then starts using the browser's back and forward buttons, the back button functionality breaks.

This is because pathname only tells you that the URL has changed—it doesn't indicate whether the change was triggered by a link click or by using the browser's back/forward buttons.


What about the native history API?

If the framework doesn’t offer support, surely the native history API should, right? After all, those browser back and forward buttons are actual desktop app buttons, so it makes sense that the browser itself should provide this information.

But no—it doesn’t.

That’s right, no support at all.

When you click the back or forward button, the browser triggers an onPopState event. That’s it. It doesn’t tell you how the user arrived at the current page.


A simple requirement that’s deceptively complex

I searched NPM for relevant packages but couldn’t find any. At one point, I was ready to drop this requirement altogether.

Still, I wanted to give it a try—surely, there had to be a way to solve this.

In the end, I managed to fulfill the requirement using the native history API.

Not long after, I realized something else: when tracking user navigation, the source URL is often fetched from document.referrer.

But with Next.js, document.referrer always stays fixed at the source link from the first visit.

After some investigation, I found that achieving accurate referrer tracking is impossible with just Next.js. The moment the user interacts with the back or forward buttons, the referrer data becomes entirely unreliable.


Published on NPM!

I figured I couldn’t be the only one facing this challenge. So after tidying up my code, I published it as a package on npm!

Here’s what it offers:

  • Detects whether the user is on the first page (solves the back button issue).
  • Correctly tracks document.referrer.
  • Determines how the user arrived at the current page (back, forward, or push).
  • Records the complete browsing history.

You can easily install it with:

npm i react-page-tracker  
Enter fullscreen mode Exit fullscreen mode

To make things clearer, I also created a demo so you can try it out.

For a practical example of the back button in action, I made this sample.

Top comments (0)