0

I am trying to set an httpOnly cookie in React while using GraphQL and Apollo. This is more or less how my React component looks like:

const verifyEmail = () => {
  const [showMessage, setShowMessage] = useState(true);
  const [text, setText] = useState("Loading... Do not close.");
  const { data, error } = useQuery(VERIFY_EMAIL);
  
  useEffect(() => {
    if (error) {return setText(genericErrorMessage)}
    if (data) {
      const cookies = new Cookies();
      cookies.set("token", data.verifyEmail.token, {
        expires: data.verifyEmail.expiry,
        secure: (process.env.SECURE_COOKIE === "true"),
        httpOnly: true,
        path: "/"
      })
      return setText(data.verifyEmail.message);
    }
  }, [error, data])

  return (
    <div>
      {showMessage && (<ShowMessage setShowMessage={setShowMessage} text={text] />)}
    </div>
  )
}

The idea here is to use the response data from the GraphQL api to set the cookie. However, whenever I try to do it, I get the following error: "Cookie 'token' has been rejected because there is already an HTTP-Only cookie but script tried to store a new one". Perhaps I'm getting this error because httpOnly cookies cannot be accessed via JavaScript and React is a JavaScript framework that runs in the user's browser. In any case, I wonder if there is a way to achieve this. I've seen online people doing it using express and axios, but not with GraphQL queries and an Apollo client. My solution for the moment has been to set the httpOnly option to false.

David
  • 41
  • 1
  • 8
  • 1
    Does this answer your question? [Set a cookie to HttpOnly via Javascript](https://stackoverflow.com/questions/14691654/set-a-cookie-to-httponly-via-javascript) – Mario Nikolaus Oct 28 '21 at 12:15

1 Answers1

0

no, instead httpOnly exists to prevent cookies from being manipulated on the client. httpOnly Cookies must be handled on the server, not the client.

R.M. Reza
  • 725
  • 1
  • 8
  • 20