1

i did switch from apollo-boost to apollo-client and i did check the docs and i did find that they set the token via localStorage but the problem is i don't have any token in my local storage the only token that i have is in the browser cookies so basically am looking for a way to pass the token from cookies to apollo-client

    const httpLink = createUploadLink({
          uri: 'http://localhost:9999',
          credentials: 'include'
      });


    const authMiddleware = new ApolloLink((operation, forward) => {
            // Retrieve the authorization token from local storage.

              const token = localStorage.getItem('token');
              console.log(token); //undefined

              // Use the setContext method to set the HTTP headers.
             operation.setContext({
               headers: {
                   authorization: token ? `Bearer ${token}` : ''
                 }
        });

          // Call the next link in the middleware chain.
           return forward(operation);
      });

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

1 Answers1

0

You can follow the steps here on how to retrieve data out of cookies: Get cookie with react

So if you use js-cookie, your authMiddleware function would look like this:

import Cookies from 'js-cookie';

const authMiddleware = new ApolloLink((operation, forward) => {
    // Retrieve the authorization token from browser cookies.

    const token = Cookies.get('token');
    console.log(token);

    // Use the setContext method to set the HTTP headers.
    operation.setContext({
        headers: {
            authorization: token ? `Bearer ${token}` : ''
        }
    });

    // Call the next link in the middleware chain.
    return forward(operation);
});
Mitchell
  • 125
  • 1
  • 6