2

I am getting token from fetch method in React while I am sending appropriate credentials, but I don't know how to store JWT token in cookie, and later reused it. Below is code block:

fetch('http://localhost:5000/api/authenticate/login', {
  method: 'POST',
  headers: {'Content-type': 'application/json'},
  body: JSON.stringify(loginInfo),
}).then(function (response) {
  return response.json();
}).then(function (json) {
  alert(json.token);
}).catch(function (ex) {
  console.log("parsing failed", ex);
});
Qiniso
  • 2,587
  • 1
  • 24
  • 30
mpp94
  • 23
  • 1
  • 6

2 Answers2

0

To store a cookie in the browser use

document.cookie=`${cookieName}=${cookieValue};${cookieOptions}`

See specs here.

If you want to set the cookie from the server, use the set-cookie header, see here

matmiz
  • 70
  • 9
0

Rather than storing token in your browser, you should think about how to secure your connection properly.

If that's not the issue, you can store it in cookies or localStorage for what you will find plenty of tutorials on google. (I like this "hooks approach" in react)

But to use JWT token properly you should store send it in response as the HttpOnly cookie. See those implementations or nodeJS implementation

And the browser should attach the token on every new request on it's own. See here

Melounek
  • 764
  • 4
  • 20