reactjsnext.js

Can I detect if using Next.js router.back() will leave my site and do a router.push('/') instead?


I currently have a "go back" link on a page that currently uses router.back() in the onClick handler to return to the previous page, which normally works if the current page was navigated to within my site, but if the page was navigated to directly (say, via a bookmark or a pasted URL) then I would like the "go back" link to do a router.push('/') to go back to my home page instead. I don't know how to determine if the previous browser history URL is outside my site to do the router.push() instead of the router.back(). Anyone have any suggestions?


Solution

  • Unfortunately, document.referrer doesn't work with Next correctly. The preferred method would be utilising a session storage to save previous and current paths using useEffect hook in _app.js

    ...
    
      const storePathValues = () => {
        const storage = globalThis?.sessionStorage;
        if (!storage) return;
        // Set the previous path as the value of the current path.
        const prevPath = storage.getItem("currentPath");
        storage.setItem("prevPath", prevPath);
        // Set the current path value by looking at the browser's location object.
        storage.setItem("currentPath", globalThis.location.pathname);
      }
    
     useEffect(() => storePathValues, [router.asPath]);
    
    ...
    

    With this, you can evaluate from which page the user came and then utilize either router.back() or router.push().