React: Delete cookie when user closes the browser

24k Views Asked by At

I'm using the library react-cookie (https://www.npmjs.com/package/react-cookie) and I want to delete the user cookies when the browser or tab is closed. I used ComponentWillUnmount in my Approuter, but that doesn't work when the browser is closed. Anyone know how to achieve this?

import React from 'react';
import {Router, Route, Switch} from 'react-router-dom';
import history from '../data/history';
import { withCookies, Cookies } from 'react-cookie';
import { instanceOf } from 'prop-types';


class AppRouter extends React.Component{

static propTypes = {
    cookies: instanceOf(Cookies).isRequired
};


constructor(props){
    super(props)
}

componentWillMount(){
    const {cookies} = this.props;
    cookies.remove('userInfo');
}

render(){
    return(
        <Router history={history}>
            <div>
                <Header/>
                <div className="main-container">
                    <Switch>
                        //routes
                    </Switch>
                    <Footer/>
                </div> 
            </div>
        </Router>
    );
}
}

export default withCookies(AppRouter);

The router does receive the cookies so why can't I remove it with componentWillUnmount? And how do I remove them?

4

There are 4 best solutions below

0
On

Not really React specific but you can use this :

window.addEventListener("beforeunload", (ev) => 
{  
    ev.preventDefault();
    cookies.remove('userInfo');
});

Maybe call it on mount so you can have access your class instance.

0
On

This may help you...

componentDidMount(){
    window.addEventListener(
        "beforeunload",
        cookies.remove('userInfo')
    );
}
1
On

When you create cookie. please set expires to 0. e.g

cookies.set('userInfo', name, { expires: 0 });

Then this cookie will be expired when browser closed.

0
On

Old post but today I was needing this and did some search and found nothing, until I came up with an easy solution. Posting here hoping it will help someone.

You just need to add the following to your 'index.js':

const handleBeforeUnload = () => {
  Cookies.remove('userinfo');
};
window.addEventListener('beforeunload', handleBeforeUnload);