2

I have a Next.js / React.js project I'm working on and I'm trying to redirect to a certain page when browser's back button is clicked. My approach is as follows

useEffect(() => {
    Router?.beforePopState(({ as }) => {
        if (as !== router.asPath) {
            handleRouteChange({ toHref: getRoutingPath('HOME') }, Router.push);
        }
        return true;
    });
        
    return () => {
        Router?.beforePopState(() => true);
    };
}, [dispatch, router]);

And this code works. When I click the back button, it takes me to the home page as intended.

But the issue is, when I click on the back button, it takes me to the previous page for a second and then redirects to the home page. How can I prevent going to the previous page at all?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
CraZyDroiD
  • 6,622
  • 30
  • 95
  • 182
  • refer this https://stackoverflow.com/questions/39342195/intercept-handle-browsers-back-button-in-react-router#:~:text=It%20depends%20on%20the%20type,intercept%20the%20browser%20back%20button. – sathish kumar Apr 22 '22 at 09:33

1 Answers1

5

You can return false from the beforePopState callback to disable Next.js handling the routing automatically and handle it yourself.

From the router.beforePopState documentation:

If cb returns false, the Next.js router will not handle popstate, and you'll be responsible for handling it in that case. See Disabling file-system routing.

useEffect(() => {
    router.beforePopState(({ as }) => {
        if (as !== router.asPath) {
            handleRouteChange({ toHref: getRoutingPath('HOME') }, Router.push);
            return false;
        }
        return true;
    });
    
    return () => {
        router.beforePopState(() => true);
    };
}, [router]);
juliomalves
  • 42,130
  • 20
  • 150
  • 146