Search code examples
reactjsfirebasecookiesfirebase-authenticationnext.js

Firebase Auth: getIdToken on every fetch or set cookie?


I'm currently working on a Next.js (React) project, where I use Firebase Auth for authentication. I use this to connect to a REST API back-end, which receives the user token Firebase provides (via getIdToken()).

Because the IdToken changes every now and then, I'm currently reqesting the latest IdToken before sending a fetch request like this:

  const fetcher = (url: string) => {
      return user.getIdToken().then((token) =>
        fetch(url, {
          method: "GET",
          headers: new Headers({
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          }),
        }).then((res) => res.json())
      );
  };

This setup actually works, but I was wondering if it's considered efficient/best-practice? I see a lot of examples out there where the IdToken is used to set a cookie (eg. firebase docs, next.js example).

I could see why when using SSR, since getIdToken() can't be called there. But my application only uses client-side data fetching. Would there be any benefits for me moving away from my current approach to using cookies?


Solution

  • The Firebase Authentication SDK already caches the token in local storage, so there's no need for you to cache it elsewhere again.

    In fact, the token is refreshed every hour, and the Firebase Authentication SDK refreshes it automatically in the background. If you cache the token yourself, you might end up using an outdated token.

    So I'd recommend always calling getIdToken() when you need the ID token. Of course it's fine to store it in a variable, and use that in a single code block (code that runs at pretty much the same time).

    Using a cookie to pass the token to your server is fine, as is using the Authorization header as you do now. The latter is more common, but a cookie works too.