React: Delete cookie when user closes the browser

djamaile picture djamaile · Nov 26, 2018 · Viewed 19.5k times · Source

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?

Answer

Jin picture Jin · Nov 26, 2018

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.