Lucky
Lucky

Reputation: 369

How to delete web application cookies in react js

I am new in reactJs I want to delete cookies and login session on logout button to diconnnect user's session. But I unable to access cookies in the code.

Please help.

Upvotes: 11

Views: 85543

Answers (4)

Tugrul Yildirim
Tugrul Yildirim

Reputation: 491

There is a simple way to do that.

First install js-cookie package

npm i js-cookie

Then

Cookies.remove('name')

That is all you need.

If you want to learn more about js-cookie follow this url : https://github.com/js-cookie/js-cookie

And then you can create a hook to handle authentication session. I prefer to use redux to handle states and I store them in a cookie generally or localstorage.

Upvotes: 3

Gaurav Mogha
Gaurav Mogha

Reputation: 400

Deleting cookie on page load

useEffect(() => {
      if(anyCondition){
        document.cookie = '<cookieName>=; Max-Age=0;secure';path=<requiredpath>;
      }
  }, []);

Upvotes: 0

adR
adR

Reputation: 528

If you are setting the cookie on a response in a login route 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.

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 you're 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/logout
// @access  Private
const logout = async (req, res) => {
    // Set token to none and expire after 5 seconds
    res.cookie('token', 'none', {
        expires: new Date(Date.now() + 5 * 1000),
        httpOnly: true,
    })
    res
        .status(200)
        .json({ success: true, message: 'User logged out successfully' })
}

module.exports = {
    login,
    logout,
}

Upvotes: 12

David
David

Reputation: 948

You can access cookies through document.cookie. In order to remove a cookie, you can set the expiration date to a date in the past:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Solution is described in here: https://www.w3schools.com/js/js_cookies.asp

There are also helper libraries to work with cookies (e.g. https://www.npmjs.com/package/react-cookie), but those will increase your bundle size slightly.

Upvotes: 9

Related Questions