How can I add a variable to all requests in apollo client?

How can I add a variable to all requests in apollo client?


1

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]),
});

2 Answers
2


0

const fetch = require('node-fetch')
const { ApolloClient } = require('apollo-client');
const { HttpLink } = require('apollo-link-http');
import { InMemoryCache } from 'apollo-cache-inmemory';
const uri = `https://graphql.contentful.com/content/v1/spaces/{spaceID}/environments/{branch}`;
const link = new HttpLink({
uri,
fetch,
headers: {
    Authorization: 'Bearer ***********token***************'
}});
const client = new ApolloClient({
cache: new InMemoryCache(), // <-- ADD ME
link,
defaultOptions: {
    query: {
        fetchPolicy: 'network-only',
        errorPolicy: 'all'
    }
}});

module.exports = client;


0

Try to set your variable using the setContext method

const httpLink = new HttpLink({ uri: process.env.REACT_APP_BASE_URL_API });
const addVariableMiddleware = new ApolloLink((operation, forward) => {
    operation.setContext({
        variables: {
            ...operation.variables,
            newVariable: "nuevavariable",
        },
    });
    return forward(operation);
});

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

Note that I am using concat approach.

That works for me



Leave a Reply

Your email address will not be published. Required fields are marked *