title: When to refresh firebase's tokenID
body: <p>I'm developing a web app using React for the frontend and Django for the backend. The UI is fully handled by React and is consuming the Django REST API.</p>
  <p>I chose firebase as the authentication provider and I implemented it as follows:</p>
  <ul>
  <li>the server (Django) connects to firebase and exposes auth endpoints to react.
  <ul>
  <li>e.g. Django's <code>/api/login</code> makes a POST request to <a href="https://firebase.google.com/docs/reference/rest/auth" rel="nofollow noreferrer">Firebase Auth REST API</a> and forwards the response (or parts of it) to the frontend</li>
  </ul>
  </li>
  <li>the authorization is based on a JWT <code>tokenID</code> provided by firebase</li>
  </ul>
  <p>Everything works as expected, but the firebase <code>tokenID</code> <strong>expires after one hour</strong> and needs to be refreshed using the <code>refreshToken</code>, action that requires a <code>POST</code> req to firebase's servers.
  I persist both these tokens on the frontend, but I can't come up with a way to make sure that <code>tokenID</code> is valid before every request to the server. I also persist the unix time when the token will be revoked.</p>
  <p>As I do not want <strong>any</strong> firebase code on the client side, I see a couple of options:</p>
  <ol>
  <li>use a <code>setTimeout()</code>. On login set the timer to one hour and on a page reload set it to the difference between when the token expires and <code>new Date()</code>.
  <ul>
  <li>would this be inefficient? to have a pending timer in the background?</li>
  </ul>
  </li>
  <li>check and refresh if necessary before each api call.
  <pre><code>async function fetchSomething(tokenID: string) {
     tokenID = await refreshIfNecessary(tokenID);
     fetch(&quot;api/endpoint&quot;, {
         method: &quot;POST&quot;,
         headers: {
            Authorization: tokenID
         }
     }.then(r =&gt; {...})
  }
  </code></pre>
  <ul>
  <li>But this would be some ugly code as I'd need to repeat <code>tokenID = await refreshIfNecessary(tokenID);</code> in every api function</li>
  </ul>
  </li>
  <li>don't try to refresh the token on the frontend, but when the API gets an expired tokenID refresh it and send along the requested data the new token
  <ul>
  <li>this adds a lot of complexity both on the ui and on the server</li>
  </ul>
  </li>
  </ol>