How to get response header from useQuery of Apollo Client
Asked Answered
C

1

6

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

Canthus answered 16/5, 2020 at 22:48 Comment(7)
why do you need this?Phototopography
For troubleshooting of errors.Canthus
what kind exactly? for data related errors usually error property gives enough info ... you can get network errors, too... just explore this objectPhototopography
@Phototopography 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.Canthus
you can reach response in error-link (apollographql.com/docs/react/data/error-handling/…)Phototopography
@Phototopography I can get response but I still don't see headers. response contains data and errors. None of them has headers.Canthus
https://mcmap.net/q/650033/-apollo-link-response-headers ?Phototopography
L
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
});
Liverwort answered 17/5, 2020 at 3:37 Comment(2)
Is there anything special I need to do with ErrorLink? When an error happens, the error object still doesn't contain headers,Canthus
Same here. operation.getContext() does not contain property response. I am trying to access response header but not able to.Moolah

© 2022 - 2024 — McMap. All rights reserved.