11

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.

4 Answers 4

12

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,
}
Sign up to request clarification or add additional context in comments.

2 Comments

How to do that when the client is offline? Currently working on a PWA with offline mode.
I can't remove cookie, Because i have two different domains for frontend and server. But i can set token when user logs in.
9

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.

3 Comments

In my case cookies are not manually in the code.But it is added while logged in and respective sessionsid are added in the browser cookies and that I want delete.(I access want delete cookies which are generated during login)
So if you want to access cookies in JavaScript that were set by the server, make sure that the cookie flag httpOnly is set to false. However, as this lowers the security of the web application, I would suggest you to remove the cookie on the server side. Example in express: expressjs.com/en/4x/api.html#res.clearCookie
And when you remove the cookie, make sure to also invalidate the session on the server.
4

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.

Comments

0

Deleting cookie on page load

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.