1

I want to implement session handling in the way that if the user closes the browser or tab all sessions are expired/destroyed. But I want to keep all the sessions if the user is navigating to another website. How can I do this in Nextjs?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

-2

You can use an event listener for an unload event: https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event

But given that you're in React/Next.js land, you'll likely want to hook up that listener inside a useEffect hook, and if you're going to do that ...

... you can simply skip the event listener entirely, and use the return value of the useEffect as your "unload" handler.

As explained here (https://reactjs.org/docs/hooks-effect.html) when you return a function from inside a useEffect, that function gets called when the component is removed from the page.

If you add the code you want to trigger "onUnload" into the returned function from a useEffect on your "App" component, this will have the same effect as using an unload event listener.

// App.js
import { useEffect}, React from 'react'

App = () => {
   useEffect(() => {
       return () => {
         // add code to trigger when the user leaves here
       }
   })
}
machineghost
  • 33,529
  • 30
  • 159
  • 234
  • But how can I decide if the tab is closing or navigating to another website? According to my knowledge window.onload will run on both times (navigate/close) – Usama Tahir Oct 15 '21 at 17:33
  • As noted in https://stackoverflow.com/questions/14711262/getting-url-of-next-page it is not possible for your page to know where the user is going when they leave. – machineghost Oct 15 '21 at 17:35
  • Actually, I take that back; if you use Google Analytics (https://www.orbitmedia.com/blog/whered-they-go-track-every-exit-click-using-google-tag-manager-in-10-steps/) it seems you can differentiate. Unfortunately I'm not sure how GA is accomplishing that. – machineghost Oct 15 '21 at 17:37