How to detect when user leaves the page and display a confirmation dialog?

Learn how to use React and Next.js to show an alert asking the user to confirm they want to exit a page using the window beforeunload event listener.
Last updated on December 27, 2023
Frameworks

When handling a data mutation on your page, it can be beneficial to prevent the user from leaving or closing the page until the action has fully completed.

This guide will show an example of this pattern using React and Next.js.

The browser provides an event listener you can use to handle the user attempting to close the window or tab called beforeunload. We can add a global event listener for this event and use our React state to derive whether it should ask for confirmation or not.

// This could be useState, useOptimistic, or other state
let pending = false;
useEffect(() => {
if (!pending) return;
function beforeUnload(e: BeforeUnloadEvent) {
e.preventDefault();
}
window.addEventListener('beforeunload', beforeUnload);
return () => {
window.removeEventListener('beforeunload', beforeUnload);
};
}, [pending]);
Ask for user confirmation before existing a page with a pending mutation.

Couldn't find the guide you need?