0

I want to store the access tokens in cookies so that they are shareable across tabs, but my requirement is I want to clear the tokens when all the browser tabs are closed or the entire browser is closed. So I am really not sure what to provide in the expires column so that it can clear them on closing the browser tab.

I am not using localStorage because it is tough to clear tokens when the browser is closed, and the event listeners are not up to the mark.

And the same case for Session storage, it works like a charm, but it is hard to pass the token across tabs, and still using some workarounds, it is not up to the mark

So can anyone please help me on how to work on this requirement using cookies in react?

Thanks in advance!!!

Dante1021
  • 304
  • 7
  • 20
  • I don't think there's any API for this so if your workarounds aren't working for you, I think you're out of luck. – Joshua Wood Jul 12 '22 at 07:56
  • 2
    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes: _"`Expires=` - [...] If unspecified, the cookie becomes a session cookie. A session finishes when the client shuts down, after which the session cookie is removed."_ But also pay attention to what it says next, _"Warning: Many web browsers have a session restore feature that will save all tabs and restore them the next time the browser is used. Session cookies will also be restored, as if the browser was never closed."_ – CBroe Jul 12 '22 at 07:59
  • @CBroe, Firstly thanks for the reply, and I tried in chrome by omitting the expires property so it automatically sets the value as **Session**, but when I closed the tab and came back the cookie still persist. – Dante1021 Jul 12 '22 at 08:13
  • https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#define_the_lifetime_of_a_cookie: _'Session cookies are deleted when the current session ends. **The browser defines when the "current session" ends**'_ - so closing a single tab might not be enough, you might need to shut down the whole browser. – CBroe Jul 12 '22 at 08:16
  • @CBroe, that's exactly what I witnessed now, thanks bud, learned something new today. – Dante1021 Jul 12 '22 at 08:18
  • @CBroe, Do you have any idea on how to clear them too on closing the tab? – Dante1021 Jul 12 '22 at 08:38
  • Try to use beforeunload [event with this answer](https://stackoverflow.com/a/179514/19220606). The event will fire when user is leaving the window. Hope this helps you!. – yashlodhi Jul 12 '22 at 09:03

0 Answers0