Want to have an event handler for the browser's back button with next.js

Viewed 11473

I am having a modal which while opening pushes a hash to url example.com/#modal, on browser back button click, I want to recognise that event so that I can toggle the state of modal. the point is, since Im using it with next.js (server side rendering), I will not be having access to window object (correct me if I am wrong). so I need an alternate way to handle the event of browser back button.

3 Answers

To add to Artinium's answer with a pratical example for your case, you can use next/router's beforePopState to act on changes to the session history navigation (back/forward actions), and make sure it'll only happen when leaving the current page.

useEffect(() => {
    router.beforePopState(({ as }) => {
        if (as !== router.asPath) {
            // Will run when leaving the current page; on back/forward actions
            // Add your logic here, like toggling the modal state
        }
        return true;
    });

    return () => {
        router.beforePopState(() => true);
    };
}, [router]); // Add any state variables to dependencies array if needed.

@Summy I hope your issue is resolved by now. If not you can try this for the browser back button:- Next.js + React Go back to the previous page If you want to use hashbang URLs you can't use SSR, since /# and /#/one is the same route server-side, so there is no way for the server to know what to render, it will need to send a basic template and let the client fill it, in that case, I think using CRA or Parcel with React Router and its HashRouter is a better option, that way you will have a single index.html and let the client decide what to render.

Related