0
 const client = new Client({
  url: senseopsHTTPServerURL,
  exchanges: [
    cacheExchange,
    authExchange(async utils =>{
      let token = initializeAuthState();
      return{ 
        addAuthToOperation(operation){
          if(!token) return operation;
          return utils.appendHeaders(operation,{
            Authorization:token,
          })
        },
      }
    }),
    fetchExchange,
    ...defaultExchanges,
    subscriptionExchange({
      forwardSubscription: (operation) => ({
        subscribe: (sink) => ({
          unsubscribe: wsClient.subscribe(operation, sink),
        }),
      }),
    }),
  ],
});

It's a front end code. I am using Reactjs.

Using above code how can I set headers to every request it make to GraphQL APIs.

halfer
  • 19,824
  • 17
  • 99
  • 186
Harshad BB
  • 99
  • 1
  • 8

1 Answers1

0

I solved it by using this following code.

    const client = new Client({
  url: "myBackendServerName",
  fetchOptions: () => {
    const token = localStorage.getItem("TOKEN_KEY");
    return {
      headers: { authorization: token ? token : '' },
    };
  },
  exchanges: [
    cacheExchange,
    ...defaultExchanges,
    subscriptionExchange({
      forwardSubscription: (operation) => ({
        subscribe: (sink) => ({
          unsubscribe: wsClient.subscribe(operation, sink),
        }),
      }),
    }),
  ],
});
Harshad BB
  • 99
  • 1
  • 8