In nextjs . I want to block navigation and appear a confirmation window popup when user trying to navigate to another page. the navigation should continue if the user click yes in the confirmation popup. If the user clicks the "no" in confirmation window , the user should stay in the current page.
There is no way in the official nextjs documentation about blocking a router.
2
Answers
You can use JavaScript’s
window.onbeforeunload
event to do that.See an example code below
If you are using NextJS 12 or less you can have the following:
Stack
The idea behind the components below is to get when the router fires the routeChangeStart and stop it immediately, then we have two ways of getting user confirmation, you can use the window.confirm() which cannot be styled, so you probably don’t want that or you can trigger an async function (which is used on the example), pass a callback so you can continue the action in case the user press "Yes" and throw immediately after, if you don’t do that, it will continue the route change.
BeforePopState is when you fire the go back / go forward on the router/browser.
BeforeUnload is when the user refreshes or clicks to exit the page (in this case you can only show the browser default window.
To help you understand better and implement, here is the logic I have created.
Code examples
/hooks/useWarnIfUnsaved
@/utils/ui/confirmationDialog
Usage