Next.js Discord

Discord Forum

prevent router from navigating

Unanswered
Holland Lop posted this in #help-forum
Open in Discord
Holland LopOP
I have looked around and cant really see any concise answer on how to prevent router navigation in the app router. All i see is how to listen for events in the pages router.
I basically want to prevent navigation until a user has confirmed they want to leave the page… because of unsaved changes etc.
Pretty essential for most sites.

10 Replies

@Holland Lop You would probably need useRouter hook.
Then you can have full control of navigation
also to clarify, preventing page navigation is not different between page router vs app router
@James4u <@325779506797477899> You would probably need `useRouter` hook. Then you can have full control of navigation
Holland LopOP
You mean using useRouter to handle navigation for links?
are we supposed to make sure every link on our site checks that content that is editable has been saved before navigating?
In pages router you had Router and could listen to an event that would fire before navigation and cancel the navigation, i dont think we have Router in app
There isn't any built-in feature to do what you need.
I think it's better to create a custom link component
and you prevent default navigation when it's clicked and you check what you need
@Holland Lop
Holland LopOP
Yep i ended up with a solution like that, custom link, custom userouter and some native eventlisteners.

Super hacky looking solution, would be nice to see a built in feature in the future… @James4u