Best way to refresh token every hour?

Viewed 4590

I am building a website with React and I have to send about 3 requests per every page, but first of all I have to get communication token that needs to be refreshed every hour by the way, and then use it as a base for all other requests.

I have a plan to get it as soon as App mounts and put it in state (redux, thunk) and use it in every component that subscribes to store and then put setInterval function in componentDidMount method too. Another thing that comes to my mind is to put it in local storage but that would be a bit complicated (I have to parse every time I get something from local storage).

class App extends React.Component {
  componentDidMount() {
    this.props.getToken()

    setInterval (this.props.getToken, 5000)
 }

This works pretty well, and switching between pages doesn't spoil anything, it works pretty good. Note that here 5000 miliseconds is just for trying out, I will put it to be 3500000. Is this OK or there is another way to do this? Thanks!

2 Answers

Your implementation is pretty fine although I'd make a few changes

  1. Use local storage so you don't have to refetch your token if user refreshes the page (since it'll be lost from memory). Also you'll have same benefit when working with multiple tabs. You can easily create some LocalStorageService that does all parsing/stringify for you so you don't have to worry.
  2. I'd suggest to move that logic to some kind of service where you'll control your token flow much easier - e.g. what happens if user logs out or somehow token becomes invalid? You'd have to get new token from other place than your App (since root componentDidMount will be called only once) and also you'd need to clear the current interval (on which you won't have reference with current implementation) to avoid multiple intervals.

Instead of intervals maybe you could even use setTimeout to avoid having multiple intervals in edge cases:

getToken() {
    // do your logic
    clearTimeout(this.tokenExpire);
    this.tokenExpire = setTimeout(() => getToken(), 5000);
}

Overall your implementation is fine - it can only be improved for easier maintenance and you'll need to cover some edge cases (at least ones mentioned above).

Ideally your server should put tokens on secured sessions so they are not vulberable to XSS.

If there's no such an option. I'd suggest using axios. You configure it to check the tokens on each request or response and handle the tokens accordingly.

Related