Ad

How To Add Headers To HttpLink In React Apollo

- 1 answer

I wanted to enter token into my graphql queries. Where I have to put my auth token?

Here is my code in apollo.js:

import { withData } from 'next-apollo'
import { HttpLink } from 'apollo-link-http'

export const config = {
  link: new HttpLink({
    uri: 'http://localhost:8000/graphql/', // Server URL (must be absolute)
    opts: {
      credentials: 'include', // Additional fetch() options like `credentials` or `headers`
    }
  })
}

export default withData(config)

That's how I make queries:

const MYJOBS = gql`
  {
    myJobs {
      role {
        name
      }
      school {
        name
      }
    }
  }
`

<Query query={MYJOBS}>
Ad

Answer

Finally, my friend suggested adding context to Query and it worked!

<Query
 query={ME}
 context={{
     headers: {
         authorization: JWT ${localStorage.getItem('token')}
     }
 }} >
Ad
source: stackoverflow.com
Ad