I need a middleware so I can pass a variable in all my requests. This is what I have, but isn't working.
const httpLink = new HttpLink({ uri: process.env.REACT_APP_BASE_URL_API });
const addVariableMiddleware = new ApolloLink((operation, forward) => {
operation.variables.newVariable = "nuevavariable";
return forward(operation);
});
const client = new ApolloClient({
cache: new InMemoryCache(),
link: from([addVariableMiddleware, httpLink]),
});
What does work is pass an authorization token this way:
const httpLink = new HttpLink({ uri: process.env.REACT_APP_BASE_URL_API });
const authMiddleware = new ApolloLink((operation, forward) => {
// add the authorization to the headers
operation.setContext(({ headers = {} }) => ({
headers: {
...headers,
authorization: "Bearer " + localStorage.getItem("dwm_token") || null,
},
}));
return forward(operation);
});
const client = new ApolloClient({
cache: new InMemoryCache(),
link: from([authMiddleware, httpLink]),
});