Detect when user leaves the page app directory router #51698
Replies: 3 comments 4 replies
-
One solution could be to create a client-component wrapper in the global layout file (covering all routes) to listen for route changes, like below: 'use client'
import { useEffect } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'
export function NavigationEvents() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
//page change logic here
}, [pathname, searchParams])
return null
} Its not exactly a page_leave_ event, but maybe it works for your case? |
Beta Was this translation helpful? Give feedback.
-
hi guys, new info? I would need to catch pressing back button in browser. Normally I would use |
Beta Was this translation helpful? Give feedback.
-
Finally I created a library for showing page leave confirmation in Next.js . https://github.com/LayerXcom/next-navigation-guard It works with both App Router and Pages Router. How it works is described here: |
Beta Was this translation helpful? Give feedback.
-
Greetings!
In the new app directory, when the client clicks the back button in the web browser, the Router doesn't have a "leave page" event, and I'm unsure about how to catch this event. Does anyone have a solution for this?
Thank you!
Beta Was this translation helpful? Give feedback.
All reactions