javascriptgithubgraphqlurql

Can custom headers be set for urql?


The Github GraphQL v4 API has so-called Schema Previews where you can use new schema features - but it requires a custom Accept header.

I've used the Apollo client before but I'd like to try this new app with Formidables urlq. Is there a way to set customer headers with the urql client?

Update

I think this has gone into the codebase, it's just not documented - https://github.com/FormidableLabs/urql/pull/96/files


Solution

  • Looking through the source, the following urql createClient works for me:

    const client = createClient({
      url: 'https://api.github.com/graphql',
      fetchOptions: {
        headers: {
          Authorization: `bearer ${GITHUB_TOKEN}`,
          Accept: 'application/vnd.github.packages-preview+json',
        },
      },
    })
    

    Update

    There's actually a better way to do this than my original answer. createClient accepts a function for fetchOptions. So if the token is present, it'll be added in an Authorization header

    const client = createClient({
      url: 'http://localhost:8000/graphql/',
      // add token to header if present
      fetchOptions: () => {
        const token = getToken()
        return token ? { headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github.packages-preview+json' }} : {}
      },
    })