skip to Main Content

I am currently working on a Next.js application where I’ve implemented a success page for users who have completed a payment. I want to prevent users from navigating back to the payment page by intercepting the back button press and redirecting them to the home page.

I have tried the following approaches without success:

  • Utilizing the popstate event listener.
  • Using the beforeunload event listener.
  • Manipulating the browser history with history.replaceState and history.pushState.

Despite these efforts, the back button press is not triggering the specified handling function. I’ve confirmed that the success page is being rendered, and other functionalities on the page work as expected.

 useEffect(() => {
    const handleBackButton = () => {
      router.push('/');
    };

    history.replaceState(null, null, location.href);

    window.addEventListener('popstate', handleBackButton);

    return () => {
      window.removeEventListener('popstate', handleBackButton);
    };
  }, [router]);

in the above code the handleBackButton never got called and I am redirecting to the payment page which is third party payment gateway.

I have tried router.beforePopState and this is also never got called for my case.

I’m using Next.js version 13.5.0.

Expected Outcome:

I expect that when a user presses the back button on the success page, they should be redirected to the home page. However, the handleBackButton function is not being called.

2

Answers


  1. i had used router.replace() instead of router.push() in the same situation

    Login or Signup to reply.
  2. Okay, so this is interesting…..

    Go on stackoverflow in a new tab
    Open Inspect Element and paste the following code in the console:

    const stateObj={foo:"bar"}
    window.onbeforeunload=function(){
      let url="https://stackoverflow.com/questions/77835092"
      history.replaceState(history.state||stateObj,"",url)
    }
    

    Then click a random question on the dashboard, then click back and it will redirect to this question…. so with at least replaceState, it seems you have to set it before the user goes into another page that they will press back on

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search