apollo-client-nextjs icon indicating copy to clipboard operation
apollo-client-nextjs copied to clipboard

What is the current way to add a token to the headers?

Open sm1thana opened this issue 4 months ago • 2 comments

Hi, thanks for your great product!

I try to add token to headers, but has no luck. The problem is that when I add token, a lot of other headers get missing and I get CORS error. I found how you add x-custom-delay at headers in this example https://github.com/apollographql/apollo-client-nextjs/blob/main/examples/hack-the-supergraph-ssr/app/ApolloWrapper.tsx

And add it to my code:

"use client";

import React from 'react';
import { ApolloLink, HttpLink } from "@apollo/client";
import {
  ApolloNextAppProvider,
  ApolloClient,
  InMemoryCache
} from "@apollo/experimental-nextjs-app-support";
import { setContext } from "@apollo/client/link/context";


function createClient(token: string | undefined) {

  const httpLink = new HttpLink({
    uri: '***'
  });  

  const authLink = setContext((_, { headers }) => {
    
    const tokenHeader = token ? {'AUTH-TOKEN': `${token}`} : null;

    return {
      headers: {
        ...headers,
        ...tokenHeader
      }
    };
  });

  const clientLinks = [authLink, httpLink];

  return new ApolloClient({
    cache: new InMemoryCache(),
    link: ApolloLink.from(clientLinks),
  });
}

// you need to create a component to wrap your app in
export function ApolloWrapper({
  children,
  token
 }: React.PropsWithChildren<{
  token: string | undefined;
}>) {
  
  const makeClient = React.useCallback(() => createClient(token), [token]);

  return (
    <ApolloNextAppProvider makeClient={makeClient}>
      {children}
    </ApolloNextAppProvider>
  );
}

Here are headers when "...tokenHeader" is commented at the code. I've got status 200, but access denied at response image

And here are when it's added image

Would you be so kind to tell me is my code right? I'm a little bit confused because Patrik's example here https://github.com/apollographql/apollo-client-nextjs/issues/281#issuecomment-2057927433

I tried to include objects from @apollo/experimental-nextjs-app-support/ssr but got IDE warning that it's deprecated. Thanks!

sm1thana avatar Oct 09 '24 14:10 sm1thana