router.beforePopState is never called

See original GitHub issue

What 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:closed
  • Created 2 years ago
  • Reactions:2
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
CristianCucunubacommented, Oct 5, 2021

Makes sense thank you!

1reaction
ijjkcommented, Oct 5, 2021

Yeah it behaves like this because router.push does a client-transition and allows Next.js to fire the popState event when navigating back in history but when using window.location directly it does a hard navigation and Next.js can’t fire the popState event.

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found