How do I add a Header to every Apollo to the GraphQL Backend in ReactQL

351 Views Asked by At

I want to add an Authorization header to every request I make to the GraphQL backend. I am using a Remotbackend.

The Apollo documentation has an example how to add a header: https://www.apollographql.com/docs/react/recipes/authentication.html#Header

import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

const httpLink = createHttpLink({
  uri: '/graphql',
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : null,
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

But how would I do this with ReactQL?

1

There are 1 best solutions below

0
On BEST ANSWER

In the Example Repo of ReactQL

https://github.com/reactql/example-auth

a method is mentioned:

  config.setApolloNetworkOptions({
    credentials: 'include',
  });

  config.addApolloMiddleware((req, next) => {
    const token = 'the_token'
    req.options.headers = {
      ...req.options.headers,
      authorization: token
    };
    next();
  });

This adds the header to every request!