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

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.

Leave a Comment