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?
-
If someone manually types or pastes a unique url via adress bar then you will need to capture that url via the server, whether it be nginx, apache, .net server, nodejs or whatever to redirect user back to react root page to then reroute. ā Steve Tomlin Jun 05 '22 at 22:02
-
1Don't do history or back button manipulation - it's frustrating for the user, and you can get delisted from search engines for such behavior. ā Sean W Jun 06 '22 at 01:44
-
Iām not interested in over-riding the browser back button behaviour, but rather change the semantics of a rendered link on my page. ā Birdzai Jun 06 '22 at 04:13
3 Answers
You can use window?.history?.state?.idx
to check the index of the state representing the latest visited page.
If window?.history?.state?.idx > 0
, that means that the user's been navigating on the website and you can "safely" use router.back(...).
If the url is directly pasted in the browser, this value will be equal to 0.

- 36
- 4
You can check out document.referrer
and check that the URL's hostname matches yours. If it does, you can safely use router.back(). If it doesn't, you can use router.push('/')
.

- 69
- 5
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().

- 21
- 3