1import { ApolloClient, HttpLink, ApolloLink, InMemoryCache, concat } from '@apollo/client';
2
3const httpLink = new HttpLink({ uri: '/graphql' });
4
5const authMiddleware = new ApolloLink((operation, forward) => {
6 // add the authorization to the headers
7 operation.setContext({
8 headers: {
9 authorization: localStorage.getItem('token') || null,
10 }
11 });
12
13 return forward(operation);
14})
15
16const client = new ApolloClient({
17 cache: new InMemoryCache(),
18 link: concat(authMiddleware, httpLink),
19});
1import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
2import { setContext } from '@apollo/client/link/context';
3
4const httpLink = createHttpLink({
5 uri: '/graphql',
6});
7
8const authLink = setContext((_, { headers }) => {
9 // get the authentication token from local storage if it exists
10 const token = localStorage.getItem('token');
11 // return the headers to the context so httpLink can read them
12 return {
13 headers: {
14 ...headers,
15 authorization: token ? `Bearer ${token}` : "",
16 }
17 }
18});
19
20const client = new ApolloClient({
21 link: authLink.concat(httpLink),
22 cache: new InMemoryCache()
23});