Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

301
Views
I want to remove cookies when the browser is closed but keep them while navigating between pages. How to do that?

Hy, I want to delete all the cookies and local storage when closing the browser but want to keep the cookies and local storage while navigating between pages in nextjs. I am using window.onbeforeunload event but this event is also triggered on navigating between pages. How to handle this issue.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It's solved. The method I'm using is I'm checking if the sessionStorage is active then don't call the handleAllSessions function to remove the cookies otherwise call it.

    if (
    typeof window !== 'undefined' &&
    !sessionStorage.getItem('sessionActive')
  ) {
    handleAllSessions();
  }
  function handleAllSessions() {
    if (!sessionStorage.getItem('sessionActive')) {
      document.cookie = 'suauth=; expires=2000-10-16T19:22:35.000Z;';
      localStorage.removeItem('isAuthenticated');
    }
  }
about 4 years ago · Juan Pablo Isaza Report

0

As others have mentioned in comments you probably should use sessionStorage. See Window sessionStorage for more information. Cool thing about it is that it deletes data after the session ends. But you can also delete session data within the session if you wish.

Edit: You could handle cookie and local storage data deletion on your own (when the browser is closed). Do this after you've stored whatever you need in sessionStorage. Then when you navigate around you'll still have that data in sessionStorage regardless of whether cookies or ls have it.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!