user10916649
user10916649

Reputation: 151

cookies.remove('abc') not working in reactJs

import Cookies from 'universal-cookie';

const cookies = new Cookies();
cookies.remove('abc');

console.log(cookies.getAll());

It is still printing my abc cookie.

Upvotes: 15

Views: 32267

Answers (4)

adR
adR

Reputation: 528

If you are setting the cookie on a response in a login route/controller in express backend for JWT and are using 'httpOnly' option, you are unable to access the token from the client/react, even when using a third party library like 'universal-cookie' or 'document.cookie'.

You will need to clear the cookie on the response from the backend e.g. when a user logs out in the logout controller as detailed below.

Front-end:

// React redux logout action
export const logout = () => async (dispatch) => {
    try {
        await axios.get('/api/auth/logout')
        localStorage.removeItem('userInfo')
        dispatch({ type: type.USER_LOGOUT })
    } catch (error) {
        console.log(error)
    }
}

Backend:

const User = require('../../models/userModel')
const generateToken = require('../../utils/generateToken')

// @desc    Auth user & get token
// @route   POST /api/auth/login
// @access  Public
const login = async (req, res) => {
    const { email, password } = req.body
    try {
        const user = await User.findOne({ email })
        if (user && (await user.verifyPassword(password))) {
            let token = generateToken(user._id)
            res.cookie('token', token, {
                maxAge: 7200000, // 2 hours
                secure: false, // set to true if your using https
                httpOnly: true,
            })
            res.json({
                _id: user._id,
                name: user.name,
                email: user.email,
                isAdmin: user.isAdmin,
                token: token,
            })
        } else {
            res
                .status(401)
                .json({ success: false, message: 'Invalid email or password' })
        }
    } catch (error) {
        res.status(500).json({ success: false, message: error.toString() })
    }
}

// @desc    Logout controller to clear cookie and token
// @route   GET /api/auth/login
// @access  Private
const logout = async (req, res) => {
    // Set token to none and expire after 1 seconds
    res.cookie('token', 'none', {
        expires: new Date(Date.now() + 1 * 1000),
        httpOnly: true,
    })
    res
        .status(200)
        .json({ success: true, message: 'User logged out successfully' })
}

module.exports = {
    login,
    logout,
}

Upvotes: 6

ann.piv
ann.piv

Reputation: 771

I just add this for people who may have similar problem in future, just like I had today. This may be an issue with asynchronous actions. Setting, removing cookies is asynchronous.

Upvotes: 2

Jeff Klink
Jeff Klink

Reputation: 439

Cookies need to have both path and domain appended to them to be removed. Try this:

cookies.remove("abc", {path: "/", domain: ".example.com"})  

Upvotes: 25

Sid
Sid

Reputation: 5833

May be you need to do something like

cookies.remove('abc', { path: '/' });

More info here

Upvotes: 48

Related Questions