Search code examples
reactjsauthenticationgraphqlnext.jsapollo

How Do I concatenate my Authorization Header with httpLink? Using Apollo Client and Next Js


ErrorI am working on an application which requires Authentication to create Posts, so I have made 2 objects, httpLink (which currently links to my backend) and authLink (which performs the function of passing header in the form of Bearer token.

This is my snippet for apollo-client.js which is handling this stuff

import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";

const httpLink = createHttpLink({
    uri:"http://localhost:5000"
});

const authLink = setContext(()=>{
    if (typeof window !== 'undefined') {
        token = localStorage.getItem('jwtToken');
      }
        return {
            headers:{
      
                Authorization: token ? `Bearer ${token}` : "",
              }
        } 
})

const uri = authLink.concat(httpLink);

const client = new ApolloClient({
    link: uri ,
    cache: new InMemoryCache(),

});

export default client;

Now if I try to use authLink.concat(httpLink), I get this error that the token is not defined, but on Dev tools>Application>localStorage, it shows the token is still valid.

I was also getting an error that "SyntaxError: Unexpected token < in JSON at position 0" but I am not able to reproduce this.

Normally, instead of error, it should show some posts which I have manually inserted into the db


Solution

  • Hello you can do it like that, Documentation -> https://www.apollographql.com/docs/react/networking/advanced-http-networking/

    const App = () => {
      const token = "your token"
    
      const httpLink = new HttpLink({ uri: "your endpoint" });
    
      const authMiddleware = new ApolloLink((operation, forward) => {
        // add the authorization to the headers
        operation.setContext({
          headers: {
            authorization: token,
          },
        });
    
        return forward(operation);
      });
    
      const graphQLClient = new ApolloClient({
        link: concat(authMiddleware, httpLink),
      });
    
      return (
          <ApolloProvider client={graphQLClient}>
            <YourApp />
          </ApolloProvider>
      );
    };