Set header in graphql

I want to set auth in req header to specific value but after I tried different methods and check req from browser my key is not in the req header

I am using Reactjs ,vite ,@apollo/client and running inside docker

import {
  ApolloClient,
  InMemoryCache,
  HttpLink,
  ApolloLink,
} from '@apollo/client';
import { setContext } from '@apollo/client/link/context';


 const httpLink = new HttpLink({
  uri: 'http://localhost:4000/graphql',
});

I tried with setContext

const authMiddleware = setContext(async (_, { headers }) => {
  const token = localStorage.getItem('token');

  return {
    headers: {
      ...headers,
      'Authorization': `Bearer ${token}` || '',
    },
  };
});

const link = ApolloLink.from([authMiddleware, httpLink]);
export const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
});

I tried with ApolloLink

const authMiddleware = new ApolloLink((operation, forward) => {
  // add the authorization to the headers

  operation.setContext(() => ({
    headers: {
       'Authorization': `Bearer ${token}` || '',
    },
  }));

  return forward(operation);
});

const link = ApolloLink.from([authMiddleware, httpLink]);
export const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
});

My used version for react and @apollo/client

"@apollo/client": "^3.11.8",
"react": "^18.3.1",

This is where I wrap my component with ApolloProvider

import { ApolloProvider } from '@apollo/react-hooks';
import { client } from './config/graphql.ts';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <ApolloProvider client={client}>
    <React.StrictMode>
          <App />
    </React.StrictMode>
  </ApolloProvider>

My data fetch req

   const response = await axios.post('http://localhost:4000/graphql', {
      query: GET_USERS,
    });

but nothing work as you see my header don’t have the Authorization key

I figured out what cause this so I will put my answer here for anyone come across my case

I was calling the query wrong in redux action

Error

  const response = await axios.post('http://localhost:4000/graphql', {
      query: GET_USERS,
    });

Correct

const { data, error } = await client.query({
  query: GET_USERS, // The GraphQL query
});

so this should depend on the client I created

export const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
});

6

Authorization in headers should be in lowercase “authorization” and set your method to below one for better error handling.

const authMiddleware = new ApolloLink(
(operation, forward) =>
  new Observable((observer) => {
    let handle;
    Promise.resolve(operation)
      .then((oper) => request(oper))
      .then(() => {
        handle = forward(operation).subscribe({
          next: observer.next.bind(observer),
          error: observer.error.bind(observer),
          complete: observer.complete.bind(observer),
        });
      })
      .catch(observer.error.bind(observer));

    return () => {
      if (handle) handle.unsubscribe();
    };
  }));

const request = async (operation) => {
const data = localStorage.getItem("token");

let token = null;
if (data) {
  token = data;
}
operation.setContext({
  headers: {
    authorization: token ? `Bearer ${token}` : "",
  },
})};

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật