11

How to pass Additional Header when calling mutation in React native apollo client ?

my Client is here:

import { HttpLink } from 'apollo-link-http';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';

const makeApolloClient = (token) => {
  // create an apollo link instance, a network interface for apollo client
  const link = new HttpLink({
    uri: 'http://x.x.x.x:xxxx/xxxx',
    headers: {
     Authorization: `Bearer ${token}`
    },
  });
  // create an inmemory cache instance for caching graphql data
  const cache = new InMemoryCache();
  // instantiate apollo client with apollo link instance and cache instance
  const client = new ApolloClient({
    link,
    cache
  });
  return client;
};
export default makeApolloClient;

If i need to add additional header to this same client when using query or mutation how can i do it ?

Is it possible with "apollo-link-context" ?

Rasheed
  • 542
  • 1
  • 6
  • 14

2 Answers2

26

You haven't specified your React version however assuming you use Hooks you do it as follows. If you aren’t using hooks change the doc version for the links at the bottom of this answer using the drop down in the top left.

Where you have your query:

const GET_USER = gql`
    query getUser{
     node {
       name
       age
     }
   }
`;

You’ll want to run a query with the useQuery hook:

const { loading, error, data } = useQuery(GET_USER, {
    context: {
        headers: {
            "Content-Type": "application/json"
        }
    }
})

Docs:

You can find the docs for each here: - UseQuery: https://www.apollographql.com/docs/react/essentials/queries/ - Context Headers: https://www.apollographql.com/docs/link/links/http/#passing-context-per-query

Lachlan Young
  • 1,266
  • 13
  • 15
6

This can be done by receiving the context which is set in mutation/query.

Setting Custom header in mutation

const [addTodo] = useMutation(ADD_TODO, {
    refetchQueries: [{ query: GET_TODO }], //updating the list of todos list after adding
    context: {
      headers: {
        "x-custom-component-add": "kkk-add",
        "x-origin-server": "pure-react"
      }
    }
  });

receiving context in middle ware which set in mutation/query

const httpLink = new HttpLink({ uri: "https://sxewr.sse.codesandbox.io/" });

const authMiddleware = new ApolloLink((operation, forward) => {
  const customHeaders = operation.getContext().hasOwnProperty("headers") ? operation.getContext().headers : {};
  console.log(customHeaders);
  operation.setContext({
    headers: {
      ...customHeaders
      //we can also set the authorization header
      // authorization: localStorage.getItem('jjjjjj'),
    }
  });
  return forward(operation);
});

Finally passing the middleware in Apoolo Client

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: from([authMiddleware, httpLink])
});

Here is the working sample.

https://codesandbox.io/s/passing-custom-header-in-graphql-mutation-query-l332g?file=/src/index.js

Custom header look like this enter image description here

Ankur Garg
  • 577
  • 3
  • 9