Next.js: Detect when user leaves the page

Created on 8 Dec 2019  路  11Comments  路  Source: vercel/next.js

Feature request

Is your feature request related to a problem? Please describe.

I would like to detect when the user leaves the page. I count 3 ways of leaving a page:

  • by clicking on a link
  • by doing an action that triggers router.back, router.push, etc...
  • by closing the tab (i.e. when beforeunload event is fired)

I know this kind of issue has already been opened here or here, but they had been magically closed (using some duplicate trick) without providing any solution.

Being able to detect when a page is leaved is very helpful for, for example, alerting the user some changes have not been saved yet.

Describe the solution you'd like

I would like something like:

router.beforeLeavingPage(() => {
    // my callback
})

Most helpful comment

+1 :+1: for this feature.

All 11 comments

+1 :+1: for this feature.

Have you seen the docs for Router events ?. It may do the trick.

Yes, I seen it. But it doesn't. There is no way to cancel a route.

Any updates about this feature request?

I want to prevent go to back when they click browser back button or mouse back button too.

Needed this feature just now.

I think this functionality is essential for any website with forms or editable content to prevent data loss.

React Router v6 has very convenient hooks for showing a window.confirm dialog with a given message when the user tries to navigate away from the current page.

See usePrompt(message: string, when = true) and useBlocker(blocker: Blocker, when = true).

How can such functionality be realized within Next.js?

I would have expected a very similar API in Next.js. I would contribute, but I'm not familiar with Next.js routing internals (React Router leverages React Context API).

I would certainly like this feature as well

A much needed feature 馃挴

This is becoming a growing issue, please vercel hear our cry.
but Have anyone tried this tool

useBeforeunload Hook (recommended)
//import { useBeforeunload } from 'react-beforeunload';

I expect it to do the work since it's built on react and I didn't seen any reliance on react-router

in a functional component

useEffect(() => {
    return () => {
        // do something
    };
}, []);
Was this page helpful?
0 / 5 - 0 ratings

Related issues

knipferrc picture knipferrc  路  3Comments

pie6k picture pie6k  路  3Comments

timneutkens picture timneutkens  路  3Comments

sospedra picture sospedra  路  3Comments

wagerfield picture wagerfield  路  3Comments