Search code examples
javascriptreactjscookiescookie-httponly

Cookies.get() is undefined


EDIT: its work / i can get the cookies value when the httpOnly = false, Why?

Im using js-cookie package,

When I open the chrome dev tools, there is a cookie token.

but when im using Cookies.get('token'), result is undefined.

and using Cookies.get() also the result is undefined.

this is my code:

import Cookies from 'js-cookie'
const [token, setToken] = useState(Cookies.get())
// const [token, setToken] = useState(Cookies.get('token'))

useEffect(() => {
    console.log(token) //undefined

    CheckAuth(token)
                .then(data => {
                    setLoggedInUser(data.user)
                })
                .catch(error => {
                    Cookies.remove('token')
                    setErrorMessage(error.message)
                })
                .finally(() => {
                    setLoading(false)
                })
}, [])

enter image description here


Solution

  • It’s a valid behaviour. Using httpOnly = true, flag while generating a cookie, makes the cookie a protected one. And if a certain browser supports httpOnly flag, It won’t allow the client side script to use such a protected cookie. Kindly find more details here, https://owasp.org/www-community/HttpOnly