Search code examples
reactjsnext.jsjwtaccess-token

Storing JWT access token in memory?


I have read that the most secure way to store the tokens is actually using a cookie for the refresh token and in-memory (like in a variable) for the access token.

While I understand this is secure, I do not really understand how it would work in practice. Would it mean that we have to create a new access token with our refresh token on each request? Or is there a way we can make it valid and copied to new variables until it is expired?

And storing an access token in memory, wouldn't that be an issue? The access token will get cleared on each refresh of the page, so each time I login, I will need to call the login endpoint again

I have tried a few things like storing the access token in localStorage, but that seems a big no no


Solution

  • While I understand this is secure, I do not really understand how it would work in practice. Would it mean that we have to create a new access token with our refresh token on each request?

    Not on each request, but on each full page reload. You would store it in something like react context, which is in memory and would make it available to your whole application. You can then have a core fetch implementation that reads this from context and puts it in the headers or whatever.

    Additionally, in that core fetch implementation, you would check for requests that error because the access token expired, and then get another access token if that happens, set it back in context, and replay whatever the request was.

    And storing an access token in memory, wouldn't that be an issue? The access token will get cleared on each refresh of the page, so each time I login, I will need to call the login endpoint again

    This is correct, but it's by design. There are tradeoffs here about how much that affects first-load time (but I wouldn't expect it to be terrible). You'd call it somewhere high up in your component tree so it happens early on. This is quite normal and I've seen it a lot.

    If you really care about that, I've seen some solutions whereby you put the access token in another HTTP-only cookie (create it serverside) for the full page load and that means it's sent for future requests. From there on in if it needs a new one it makes an API call which also uses set-cookie to write a fresh one to the client. Since it's there on the actual response to get the page itself, you avoid any waterfall of clientside requests.

    Some people just store it in local storage but then as you imply, there are also security tradeoffs there and so it's best avoided.