I am building an app in PHP Lumen which returns a token upon login. I am not sure how to proceed beyond this.
How am I supposed to maintain a session using these tokens?
Specifically, how do I store the tokens on the client side if I am using reactjs or vanilla HTML/CSS/jQuery and send them in every request I make for the secure part of my web app?
What I usually do is to keep the token in the local storage, this way I can persist the token even if the user leaves the site.
localStorage.setItem('app-token', theTokenFromServer);
Every time the user loads the page, the first thing I do is to look for the existence of the token.
token = localStorage.getItem('app-token');
If using react, I'd keep the token on the global state (using redux for example):
function loadAppToken(token) {
return {
type: 'LOAD_TOKEN',
payload: { token },
};
}
With vanilla javascript I'd keep it on my connection utility. Which might look something like the following:
const token = localStorage.getItem('app-token');
export function request(config) {
const { url, ...others } = config;
return fetch(url, {
...others,
credentials: 'include',
headers: {
'Authorization': `Bearer ${token}`
},
});
}
I'd still have a fetch utility in a react app, similar to the previous code, but I'd send the token in the options, by getting it in a redux middleware for every single request.