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

Allow dynamic headers

Open LucaFilitz opened this issue 3 years ago • 5 comments

Hello, when you create a upload link, you can only set the headers once. This is a problem when you refresh your authentication token.

Apollo allows to pass a function to the connecitonParams so that every time a request is made the token is fetched. This is better.

What is possible: createUploadLink({ uri: "SOME URI", headers: { Authorization: "Bearer " + get(token) } })

What I need: createUploadLink({ uri: "SOME URI", headers: () => { return { Authorization: "Bearer " + get(token) } } })

Currently, when I do this no headers are passed.

Could you fix this? Kind Regards Luca

LucaFilitz avatar Oct 27 '22 21:10 LucaFilitz

Is that a new-ish thing in Apollo that you can do that?

For now, you should be able to create the headers each request via a custom Apollo Link:

https://www.apollographql.com/docs/react/networking/advanced-http-networking/#customizing-request-logic

jaydenseric avatar Oct 27 '22 22:10 jaydenseric

I think it is kind of new. But not that new. Oh, yes that is corretct I didn't think about adding a middleware. Still, it would be nice to not need it :) I might open a pull request if you don't mind.

LucaFilitz avatar Oct 27 '22 22:10 LucaFilitz

It looks like selectHttpOptionsAndBody (createUploadLink.js l. 118) somehow validates the headers. Therfor you'd have to rewrite that part/ create your own function.

To be honest I do not know what it does and do not want to touch it.

=> I will use the middleware for now.

LucaFilitz avatar Oct 27 '22 22:10 LucaFilitz

This worked for me.

const httpOptions = { timeout: 15000, uri: GRAPHQL_SERVER_V1, };

const authMiddleware = setContext((operation, { headers }) => {
    return getCredentials().then(data => {
      return {
        headers: {
          ...headers,
          authorization: `Bearer ${data?.accessToken}` || null,
        }
      };
    });
  });
  

const singleLink = split(
    ({ query }) => {
        const definition = getMainDefinition(query);
        return (
            definition.kind === "OperationDefinition" &&
            definition.operation === "subscription"
        );
    },
    wssLink,
    split(
        operation => operation.getContext().hasUpload,
        from([authMiddleware, createUploadLink({ ...httpOptions, isExtractableFile: customIsExtractableFile })]),
        from([authMiddleware, httpLink])
    )
);

sashrika avatar Apr 22 '24 03:04 sashrika