---
title: How to detect when user leaves the page and display a confirmation dialog?
description: 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.
url: "https://vercel.com/kb/guide/leave-page-confirmation-dialog-before-unload-nextjs-react"
published: 2025-11-03
last_updated: 2025-11-10
authors: Lee Robinson
install_vercel_plugin: npx plugins add vercel/vercel-plugin
---

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.

## Confirm navigation away with event listener

The browser provides an event listener you can use to handle the user attempting to close the window or tab called [`beforeunload`](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event). 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.

```jsx
// 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]);
```

## More Next.js guides

- [How do I reduce my build time with Next.js on Vercel?](/kb/guide/how-do-i-reduce-my-build-time-with-next-js-on-vercel): Reduce Next.js build times on Vercel by pre-rendering fewer pages at build time, deferring generation with ISR and image optimization, and using faster build machines.
- [Integrating AWS Secrets Manager with Vercel Using Terraform](/kb/guide/integrating_aws_secrets_manager_with_vercel_using_terraform): Learn how to seamlessly integrate AWS Secrets Manager with Vercel for enhanced security and efficiency in your web deployments using Terraform with our comprehensive guide.
- [Can I redirect from a subdomain to a subpath?](/kb/guide/can-i-redirect-from-a-subdomain-to-a-subpath): Learn how to redirect from your subdomain to a subpath on Vercel with a vercel.json file or with Next.js