🚀 Preventing Navigation in Next.js 15 – Solved!
Ever built a form in Next.js and realized users could lose all their work by accidentally clicking a link, hitting back, or closing the tab? Yeah, that’s frustrating.
I first tried using beforeunload, but it turns out Next.js handles routing internally, so it doesn't fire when users navigate within the app. That’s when I dug deeper and came up with a universal solution that works across any frontend framework:
✅ Prevents link clicks unless confirmed ✅ Warns before closing/reloading the page ✅ Stops accidental back button navigation
Here's the snippet I used:
Recommended by LinkedIn
useEffect(() => {
const interceptNavigation = (event: MouseEvent) => {
const target = event.target as HTMLAnchorElement;
if (target.tagName === "A" && target.href) {
const confirmLeave = window.confirm("You have unsaved changes. Do you really want to leave?");
if (!confirmLeave) {
event.preventDefault();
event.stopPropagation();
}
}
};
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
event.preventDefault();
event.returnValue = "";
};
const handlePopState = () => {
const confirmLeave = window.confirm("You might have unsaved changes. Do you really want to leave?");
if (!confirmLeave) {
history.pushState(null, "", window.location.href);
} else {
window.removeEventListener("popstate", handlePopState);
}
};
history.pushState(null, "", window.location.href);
document.addEventListener("click", interceptNavigation, true);
window.addEventListener("beforeunload", handleBeforeUnload);
window.addEventListener("popstate", handlePopState);
return () => {
document.removeEventListener("click", interceptNavigation, true);
window.removeEventListener("beforeunload", handleBeforeUnload);
window.removeEventListener("popstate", handlePopState);
};
}, []);
This works not just in Next.js 15 but also in React, Vue, and even vanilla JavaScript. 🚀
Hope this helps someone else! Have you ever had to solve this problem? Let me know if you’d do it differently. 👇
#Nextjs #WebDev #React #JavaScript #Frontend