I've been using headers for authentication with Apollo Client. The following worked fine:
const middlewareAuthLink = new ApolloLink((operation, forward) => {
const token = localStorage.getItem('auth-token');
const authorizationHeader = token ? `Bearer ${token}` : null;
operation.setContext({
headers: {
authorization: authorizationHeader,
},
});
return forward(operation);
});
Im switching over to Apollo Boost: https://dev-blog.apollodata.com/zero-config-graphql-state-management-27b1f1b3c2c3
const client = new ApolloClient({
uri: 'MY-GRAPHCOOL-API',
fetchOptions: {
credentials: 'include',
},
request: async operation => {
operation.setContext({
headers: {
authorization: 'sadfjadsfsd',
},
});
},
clientState: {
defaults: {
CurrentUserIsLoggedIn: {
__typename: 'CurrentUserIsLoggedIn',
value: false,
},
},
resolvers: {
Mutation: {
CurrentUserIsLoggedIn: (_, args, { cache }) => {
const data = {
CurrentUserIsLoggedIn: {
__typename: 'CurrentUserIsLoggedIn',
value: args.value,
},
};
cache.writeData({ data });
},
},
},
},
});
Now I get an error and my token isnt being added:
[Network error]: TypeError: operation.setContext is not a function
First, import the onError function. 1import { onError } from "@apollo/client/link/error"; Second, create the errorLink: 1const errorLink = onError(({ graphQLErrors, networkError }) => { 2 if (graphQLErrors) { 3 console.
Resetting the cache To accomplish this, call client. resetStore . This method is asynchronous, because it also refetches any of your active queries. To reset the cache without refetching active queries, use client.
When there is a network error while trying to contact a GraphQL server, due to either the server being down or timeouts etc, then the response will be a status code of 4xx or 5xx. If the server responds anything other than 200, the response is not successful due to either being a: Bad request (400) Unauthorized (401)
There's an open pull request on GitHub that addresses this issue: [apollo-boost] pass operation prop to config.request
Until it's merged, you can just apply the changes yourself in the apollo-boost
package within your node_modules
folder and run its build script with yarn build
. Quick fix that worked for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With