verygoodsecurity / collect-js-react

MIT License
1 stars 15 forks source link

Feature Request: Allow `headers` on `submitParameters` to accept a function #55

Closed filipebarcos closed 4 weeks ago

filipebarcos commented 2 months ago

Expected Behavior

Allow headers on submitParameters to accept a callback function. I need to pass an Authentication header to the proxy/outbound URL, but I want to fetch the value for this header async/on demand.

Current Behavior

Currently, via the docs, I see that is only possible to pass an object. Would be a similar behavior as we have for data.

Context

This is because we integrate with Astra and to use their own vault, we must provide an access token for them to be able to create a card for our user on our behalf.

Tentative approaches with current behavior

<VGSCollectForm
  vaultId={import.meta.env.VITE_VGS_VAULT_ID as string}
  environment={
    import.meta.env.VITE_VGS_ENVIRONMENT as VGSCollectVaultEnvironment
  }
  cname={import.meta.env.VITE_VGS_ASTRA_CNAME as string}
  action="/v1/cards"
  submitParameters={{ headers: fetchAstraAuthHeader }}
>

the implementation of the fetchAstraAuthHeader looks like:

const fetchAstraAuthHeader = () =>
  someRequestToMyBackend().then(({ access_token }) => 
    {
      Authentication: `Bearer ${access_token}`,
    }));

The error: DataCloneError: Failed to execute 'postMessage' on 'Window'

flor-master commented 1 month ago

Hi @filipebarcos, apologies for the delay. We extended functionality and allowed async functions to set up request headers, but we added it to Collect SDK, this SDK collect-js react uses under the hood.

So, now you can try it. Code example you can find here: https://github.com/verygoodsecurity/collect-js-react/blob/main/example/src/features/CustomPayload.tsx#L80-L92 Don't forget to use the latest version of Collect SDK: new version 2.25.1

filipebarcos commented 4 weeks ago

This worked @flor-master. Thanks a bunch