router.beforePopState is never called
See original GitHub issueWhat version of Next.js are you using?
10.2
What version of Node.js are you using?
16.4
What browser are you using?
Chrome
What operating system are you using?
Mac OS
How are you deploying your application?
Other platform
Describe the Bug
I’m trying to use
const router = useRouter();
useEffect(() => {
router.beforePopState(() => {
alert('Before pop state!');
return false;
});
});
To capture the “Back Button Pressed” on browser but it always navigate back without hitting the function.
Do I need to do something else in order to make this work?
Expected Behavior
It should trigger an alert when the user hits the back button of browser.
To Reproduce
Create a page on next and add this code
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:8 (4 by maintainers)
Top Results From Across the Web
Router.beforePopState not firing · Issue #4809 · vercel/next.js
The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling...
Read more >Next Js Router beforePopState , access state of component in ...
I am using Next js Router.beforePopState event and i want to access value of useState variable which i created in react component in...
Read more >next/router beforePopState not firing : r/nextjs - Reddit
As per title, beforePopState just doesn't fire when I hit the back button. This code is a hook called in _app.js as per...
Read more >next/router | Next.js
If cb returns false , the Next.js router will not handle popstate , and you'll be responsible for handling it in that case....
Read more >Next.js — Preserve Scroll History | by Jakob Chill | Medium
The callback passed to router.beforePopState() is called when a popstate (e.g. using the browser back button) event is triggered.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Makes sense thank you!
Yeah it behaves like this because
router.pushdoes a client-transition and allows Next.js to fire the popState event when navigating back in history but when usingwindow.locationdirectly it does a hard navigation and Next.js can’t fire the popState event.