skip to Main Content

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

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",

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

enter image description here

2

Answers


  1. 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}` : "",
      },
    })};
    
    Login or Signup to reply.
  2. That setContext approach should be fine. Headers should be lowercase but will automatically connected. What I don’t see: you create that authMiddleware with setContext, but to you actually hook it up to your ApolloClient? Please show that part.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search