I have a reactjs login application and I want to store the token I get from the API to cookie or local storage, the code below is the basic authentication POST method that I use. can you show me how to store token in the cookie or local storage in reactjs? Which one is better?
const xhr = new XMLHttpRequest();
const data = "access_token=value";
const url = "https://api";
xhr.open("POST", url);
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader(
"Authorization",
"Basic " + btoa("Username:Password")
);
xhr.send(data);
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(xhr.response);
}
};
my response has a token parameter and the value of it.
Generally in web app, we used a localstorage or session to our token id in our web app. so, you can used localstorage or session. based on your project requirement you can used any one.
Exmple
localStorage.setItem('variableName', data);
you can save this way in localstorage.