Suppose I have API for login, log out. I am using Token Authentication. I have react component name Login. I can call API and I am getting token. But, I am not understanding how to save the token in a browser until log out or automatically destroy token after a moment.
2 Answers
You can create a storage module and check for available storage in client's browser.
import LocalStorage from "./localstorage"
import Cookie from "./cookie"
// Function to check availability of `localStorage`
function storageAvailable() {
try {
var storage = window["localStorage"],
x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return false;
}
}
export default function Storage() {
return storageAvailable() ? LocalStorage : Cookie
}
Using above module:
function login(redirect = '/home') {
// set your session data
storage.set({email, id})
// redirection
window.location.href = redirect
}
function logout(redirect = "/") {
storage.clear()
// redirection
window.location.href = redirect
}
const Session = {
login,
logout
}
export default Session
Now you can simply use your Session module for login and logout as Session.login() and Session.logut() respectively.
How to use cookie: How do I create and read a value from cookie?
How to use localStorage: Storing Objects in HTML5 localStorage
3 Comments
You can use universal-cookie package to set it in the cookie,
const cookies = new Cookies();
cookies.set('token', this.token, { path: '/' });
Don't forget to import(or require) Cookies from universal-cookie.
You can retrieve it back using :
cookies.get('token');
Refer to https://github.com/reactivestack/cookies/tree/master/packages/universal-cookie
You can save it in local storage as well :
localStorage.setItem('token', this.token);
But saving in the cookie would be a better idea, refer to :