When using Apollo, how to send a custom auth header from the component?

In my app, I use firebase to authenticate the user. Right now, whenever I want to send a regular API call to my backend server, I first get a unique ID token for the user through firebase. I have to generate a token for every request because they expire. Then from the server, I can use this token to authenticate the user.

In Apollo, I saw that we can set a header when initializing the app. For my scenario, this will not work. I need to be able to set the header per every request. Is it possible?

Per the official example: http://dev.apollodata.com/react/auth.html#Header which I think is the one you’re referring to, the information passed on the header is indeed per request!

As long as you keep localStorage updated with the latest token, each query/mutation call will indeed use that latest token.

Or of course, you can use some other place to store that token, it does not have to be local storage. The point is, the header is set per request, not per “app session”.

1 Like

Sorry for the late reply. It worked! I managed to get the firebase token for every request like this:

networkInterface.use([
  {
    applyMiddleware: async (req, next) => {
      if (!req.options.headers) {
        req.options.headers = {};
      }

      await firebase.auth().onAuthStateChanged(async (user) => {
        if (user) {
          const token = await firebaseGetIDToken();

          req.options.headers.authorization = token ? `ApiKey ${token}` : null;
          next();
        }
      });
    }
  }
]);

Now before every request, it will get the auth token from firebase and attach it to the API call so I can verify the user from the back end. Thank you very much for the help!

1 Like

I’m glad I could help!

1 Like