Hi!
I’m trying to set an authorization middleware yo my Apollo Client but something is not working. I can set the corresponding header correctly but my server still responds as i’m not authenticated.
Tried this:
const httpLink = new HttpLink({
uri: process.env.API_GRAPHQL,
});
const authLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
const token = localStorage.getItem("token");
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
},
};
});
const apolloClient = new ApolloClient({
link: authLink.concat(httpLink),
includeUnusedVariables: true,
credentials: "include",
connectToDevTools: true,
cache: new InMemoryCache({})
And this:
const httpLink = new HttpLink({
uri: process.env.API_GRAPHQL,
});
const authMiddleware = new ApolloLink((operation, forward) => {
var token = localStorage.getItem("token");
operation.setContext({
headers: {
Authorization: token ? `Bearer ${token}` : "",
},
});
console.log(operation);
return forward(operation);
});
const apolloClient = new ApolloClient({
link: authMiddleware.concat(httpLink),
includeUnusedVariables: true,
credentials: "include",
connectToDevTools: true,
cache: new InMemoryCache({})
I’ve also tried with createHttpLink
instead of new httpLink
, and with concat(middleware, httpLink)
instead of middleware.concat(httpLink)
.
The sent request has correctly set the token, but the response is still an auth error.
If i do not set any middleware and hard-code my token the Client works fine, something in the construction of my link is not working…
Is there something i’m missing? what are my possibilities? Is there a way I can debug my client?
Thank’s in advance.