Search code examples
javascriptlocal-storagejwtaccess-tokensession-storage

Should i get access-token from sessionStorage for each request?


So basically when I login my backend returns me a token so I store it like:

// var token is global
token = res.data.token;
sessionStorage.setItem("token", token);

And when I logout I just remove the items from sessionStorage and reset the var:

token = '';
sessionStorage.removeItem("token");

Then in all my requests I use the var to create the header

{ headers: { "Authorization": "Bearer " + token } }

But I don't know if i should keep the token var or just access the storage for each request like:

{ headers: { "Authorization": "Bearer " + sessionStorage.getItem("token"} }

Right now I just use the storage in case the user refresh the page, so he doesn't lose javascript context, because I thought is more efficient than accessing the storage for each request, but I don't know what is the best approach security-wise, or what do usually developers do?


Solution

  • It makes no difference from a security perspective; neither is more secure than the other.

    If you only need the token when doing an ajax call, don't worry about the overhead of getting it from sessionStorage. That operation doesn't take any significant time at all, certainly not compared with doing an ajax call. You'd only need to cache the result in a variable if you were using it in a tight loop doing thousands of operations (or possibly hundreds of thousands) while the user waited for them. You might want it in a variable for other reasons (convenience, for instance), but there's no efficiency argument in the case you describe.

    General rule: Worry about performance when you have a performance problem (but, you know, don't be completely silly doing things you know are horribly inefficient...). :-)