0
0
GraphqlHow-ToBeginner · 4 min read

How to Set Headers in Apollo Client for GraphQL Requests

To set headers in Apollo Client, use the ApolloClient constructor with an HttpLink that includes a headers option or use setContext from @apollo/client/link/context to dynamically add headers like authorization tokens. This ensures headers are sent with every GraphQL request.
📐

Syntax

Use ApolloClient with HttpLink to set static headers or use setContext to add headers dynamically before each request.

  • ApolloClient: Main client to send GraphQL requests.
  • HttpLink: Defines the HTTP connection and headers.
  • setContext: Middleware to modify headers per request.
javascript
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

// Static headers example
const httpLink = new HttpLink({
  uri: 'https://example.com/graphql',
  headers: {
    authorization: 'Bearer static-token',
  },
});

// Dynamic headers example
const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem('token');
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '',
    },
  };
});

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

Example

This example shows how to set an authorization header dynamically using setContext so the token is read fresh before each request.

javascript
import { ApolloClient, InMemoryCache, HttpLink, gql } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

const httpLink = new HttpLink({ uri: 'https://example.com/graphql' });

const authLink = setContext((_, { headers }) => {
  const token = 'my-secret-token'; // Normally from storage or state
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '',
    },
  };
});

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

// Example query
client.query({
  query: gql`query { viewer { id name } }`
}).then(response => console.log(response.data));
Output
{"viewer":{"id":"123","name":"Alice"}}
⚠️

Common Pitfalls

Common mistakes when setting headers in Apollo Client include:

  • Setting headers directly on HttpLink without using setContext when tokens change dynamically.
  • Not concatenating authLink with httpLink, so headers are not sent.
  • Forgetting to spread existing headers, which can overwrite default headers.
javascript
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

// Wrong: Not concatenating authLink
const httpLink = new HttpLink({ uri: 'https://example.com/graphql' });
const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      authorization: 'Bearer token',
    },
  };
});

const clientWrong = new ApolloClient({
  link: httpLink, // authLink not used
  cache: new InMemoryCache(),
});

// Right: Concatenate authLink and httpLink
const clientRight = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});
📊

Quick Reference

ConceptDescriptionUsage
ApolloClientMain client to send GraphQL requestsnew ApolloClient({ link, cache })
HttpLinkDefines HTTP connection and static headersnew HttpLink({ uri, headers })
setContextMiddleware to add headers dynamicallysetContext((_, { headers }) => ({ headers: {...headers, authorization} }))
concatCombine links so headers applyauthLink.concat(httpLink)

Key Takeaways

Use setContext to add or update headers dynamically before each request.
Always concatenate authLink with httpLink to ensure headers are sent.
Spread existing headers to avoid overwriting default headers.
Static headers can be set directly in HttpLink but are less flexible.
Authorization headers typically use the Bearer token format.