6

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

His
  • 5,891
  • 15
  • 61
  • 82
  • why do you need this? – xadm May 16 '20 at 22:57
  • For troubleshooting of errors. – His May 16 '20 at 23:08
  • what kind exactly? for data related errors usually `error` property gives enough info ... you can get network errors, too... just explore this object – xadm May 16 '20 at 23:30
  • @xadm the backend sends a correlation id as a response header. I need to get my hands on it to correlate the error with other things happening in the backend. – His May 17 '20 at 02:44
  • 1
    you can reach `response` in error-link (https://www.apollographql.com/docs/react/data/error-handling/#network-errors) – xadm May 17 '20 at 02:53
  • @xadm I can get `response` but I still don't see headers. `response` contains `data` and `errors`. None of them has headers. – His May 17 '20 at 11:00
  • https://stackoverflow.com/a/47479911/6124657 ? – xadm May 17 '20 at 11:26

1 Answers1

8

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
});
Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • 1
    Is there anything special I need to do with ErrorLink? When an error happens, the `error` object still doesn't contain headers, – His May 17 '20 at 11:02
  • Same here. operation.getContext() does not contain property response. I am trying to access response header but not able to. – Sandy Jul 21 '21 at 05:31