Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
How to send common variable with every request in react-apollo?

I am trying to send a common variable with every request through react-apollo. So I tried with ApolloLink to add variable in the operation, but while inspecting the network I can't see the variable going with the query.

Here's how I have written the middleware:


const authLink2 = new ApolloLink((operation, forward) => {
    operation.variables['entityId'] = '633'// localStorage.getItem('entityId');

    operation.setContext(({ headers }) => {
        const token = localStorage.getItem(AUTH_TOKEN);
  
        return {
            headers: {
                ...headers,
                Authorization: token ? `JWT ${token}` : "",
            }
        }
    });
    
    // until this log I can see the entityId variable has been appended
    console.log('operation', operation); 
    return forward(operation);
});

// creating ApolloClient
export const client = new ApolloClient({
    link: authLink2.concat(httpLink),
    cache
});

If this is not possible with ApolloLink middlware, please help me find a way to append the variable with every request.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

you can sent anything in the header like this and access it in backend

const httpLink = createHttpLink({
  uri: `${configEnv.BASE_URL}/graphql`,
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem(LOCAL_CONSTANT.TOKEN);
  const userToken = token ? JSON.parse(token) : null;
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      Authorization: userToken?.accessToken ? `Bearer ${userToken?.accessToken}` : '',
      testingVariable: '633'
    },
  };
});

export const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda