Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
sm1thana opened this issue Oct 9, 2024 · 6 comments
Closed

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

sm1thana opened this issue Oct 9, 2024 · 6 comments

Comments

@sm1thana
Copy link

sm1thana commented Oct 9, 2024

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
#281 (comment)

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

@sm1thana
Copy link
Author

Rewrite concatenation like at common apollo client
https://www.apollographql.com/docs/react/networking/advanced-http-networking#customizing-request-logic

and noticed that it works fine if added header is 'authorization'. If I change it to 'AUTH-TOKEN' or authtoken, than some headers get missing.

I can't use custom name for added header?

Current code:

"use client";

import React from 'react';
import { ApolloLink, HttpLink, concat } 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 authMiddleware = new ApolloLink((operation, forward) => {
    
    const tokenHeader = token ? {'AUTH-TOKEN': `${token}`} : null;

    operation.setContext(({ headers = {} }) => ({  
      headers: {  
        ...headers,  
        authorization: token || null,
        // ...tokenHeader
      }  
    }));  
  
    return forward(operation);
  
  })

  return new ApolloClient({
    cache: new InMemoryCache(),
    link: concat(authMiddleware, httpLink),
  });
}

export function ApolloWrapper({
  children,
  token
 }: React.PropsWithChildren<{
  token: string | undefined;
}>) {
  
  const makeClient = React.useCallback(() => createClient(token), [token]);

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

@phryneas
Copy link
Member

You should be able to use any kind of header here. We just forward that to fetch.

@sm1thana
Copy link
Author

@phryneas Have you any thoughts why can request became invalid than?
It became invalid even if I change authorization: token || null, to authorization2: token || null,

Mozilla gives 400 status for request with added header named not authorization.

@sm1thana
Copy link
Author

@phryneas I'm very sorry for bothering, but the problem was at server settings. We've temporary added CORS_ALLOW_ORIGIN=['*'] and error has gone. Request sends without errors, all headers are valid.
Will try to understand why header differs from 'authorization' сause an error.

Copy link
Contributor

Do you have any feedback for the maintainers? Please tell us by taking a one-minute survey. Your responses will help us understand Apollo Client usage and allow us to serve you better.

@phryneas
Copy link
Member

Sorry for the late reply from my side, I had to give a conference talk yesterday so I'm a bit swamped right now 😓

Great to hear you found it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants