Next JS 13 intercept route change
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import type { NavigateOptions } from 'next/dist/shared/lib/app-router-context.shared-runtime';
/**
* Source: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
*/
const beforeUnloadHandler = (event: BeforeUnloadEvent) => {
// Recommended
event.preventDefault();
// Included for legacy support, e.g. Chrome/Edge < 119
event.returnValue = true;
return true;
};
/**
* Prompt the user with a confirmation dialog when they try to navigate away from the page.
*/
export const useConfirmNavigation = () => {
const router = useRouter();
useEffect(() => {
const originalPush = router.push;
const newPush = (href: string, options?: NavigateOptions | undefined): void => {
const isConfirmed = window.confirm('Are you sure you want to leave? Changes you made will not be saved.');
if (isConfirmed) {
originalPush(href, options);
}
};
router.push = newPush;
window.onbeforeunload = beforeUnloadHandler;
return () => {
router.push = originalPush;
window.onbeforeunload = null;
};
}, [router]);
};
https://github.com/vercel/next.js/discussions/41934#discussioncomment-8174608