jasonkuhrt / graphql-request

Minimal GraphQL client

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Dynamic Headers: use async function to get headers

0xalecks opened this issue · comments

Perceived Problem

Currently, we can set dynamic, per request, headers by setting the headers to a function that resolve them:

  const client = new GraphQLClient(graphqlUrl, {
    headers:() => {
      return {
        Authorization: "Bearer XXX"
      };
    },
  });

Ideas / Proposed Solution(s)

A common security pattern on SPA apps that use JWTs is to set their expiration very low, every 2 hrs for ex, which means we need to check if the JWT is expired, and refresh it before setting it as a header.

Would be great to be able to do this logic inside the headers function but it would require that function to support async since refreshing the token is usually an api call to the identity provider.

Ideally, something like this would work:

  const client = new GraphQLClient(graphqlUrl, {
    headers: async () => {
      const token = await getOrRefreshToken();
      return {
        Authorization: `Bearer ${token}`,
        "X-Hello": Date.now().toString(),
      };
    },
  });

I found a description of how to implement authorization https://github.com/jasonkuhrt/graphql-request/blob/HEAD/examples/other-middleware.ts

Awesome, thanks!