2
votes

I build a Rest-API which handle request by using JWT and refresh token. But i am not sure how to store it on client side.

Should I store both it in cookies with httponly flag?

Should i store both in cookies or one in local storage for example shared preference(Android App)?

I am very interested in what is the best practice to handle these token on client side?

2

2 Answers

1
votes

Standard recommendations:

  • In a mobile UI store tokens in OS secure storage
  • In a Web UI store the access token in memory
  • In a Web UI refresh tokens in cookies work best

It requires a lot of discipline to do properly. My blog has posts and code samples you can run to understand this stuff. Maybe start here:

-1
votes

The best solution for this IMO is local storage. Cookie files can be useful with browsers - but they can be cleared by the user or automatically (after closing a private window).

How to set the cookie (including the expiry date):

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

How to read cookie:

const cookie = getCookie("value");
if (cookie === "value2") {
console.log("I get value 2");
} else {
console.log("I get other value");
}

How to set the local storage:

localStorage.setItem('name', 'value');

How to read the local storage:

const storage = localStorage.getItem('name');
if (storage === 'value2') {
console.log("I get value 2");
} else {
console.log("I get other value");
}

If you want more information, write a comment. Remember if my answer was helpful - mark it as helpful