Search code examples
javascriptgraphqlreact-hooksapollo-clientresponse-headers

How to get response header from useQuery of Apollo Client


I haven't been able to find a way to do this at all. Does anyone know if this is supported? Thanks.


Solution

  • ApolloClient's methods for making requests, and the React Hooks that use them, serve as an abstraction over how the data is actually fetched. It could come from a remote server over HTTP, from the cache, from directly executing the request against a schema, etc. As a result, they don't expose any information regarding how the data was fetched in the first place, including transport-specific information like HTTP headers.

    If you need to access this information, the appropriate place to do so would be inside a Link that you'd prepend to your HttpLink -- either an existing one like a ContextLink or ErrorLink, or some custom Link you roll yourself. If you're doing this in an error-handling context, then ErrorLink would be your best bet, as suggested in the comments.

    HttpLink injects the raw response from the server into the context object used by all Links (see here). Assuming you're using the default fetch API as the fetcher, this response will be a Response object.

    So you can do something like this:

    const link = onError(({ graphQLErrors, networkError, operation }) => {
      const { response } = operation.getContext();
      const { headers, status } = response;
      
      // do something with the headers
    });