typescriptnext.js

How to add close confirmation to page in Next.JS with Typescript


I am attempting to make a close confirmation popup in Next JS using typescript, I searched around but I could only find solutions that were: outdated, for javascript, or weren't possible with Next JS or React.

Close Confirmation Popup

I tried to use

window.onbeforeunload(){}

but, of course, Next JS does not use a ' window '

I tried to use ' useEffect ' but I could not figure out how to implement it.


Solution

  • You can use the following way. I assume that you implement a function handleWindowClose which contain the logic you want.

    What you need to do in nextjs environment, to not run the code on server side or to ensure it runs there as well by using null check. You can image that there is no window on server ;)

    useEffect(() => {
     window.addEventListener('beforeunload', handleWindowClose);
    });
    

    This is only if you leave the complete website by typing new url or what ever. If you want to check internally - the user leaves a specifiy part of the website you should use the router. In the following example i assume the logic is part of the method handleBrowseAway

    router.events.on('routeChangeStart', handleBrowseAway)
    

    By the way, js can be used as typescript.