ethers.js icon indicating copy to clipboard operation
ethers.js copied to clipboard

Pass fetch options to browser providers

Open stephenlacy opened this issue 2 years ago • 4 comments

Describe the Feature

Currently when communicating with RPC endpoints (or gateways) additional fetch options are not able to be passed in: https://github.com/ethers-io/ethers.js/blob/278f84174409b470fa7992e1f8b5693e6e5d2dac/src.ts/utils/geturl-browser.ts#L49

For instance, cors or credentials (fetch credentials vs Authorization header) options.

Code Example

const fetchReq = new ethers.FetchRequest(URL, { credentials: "include" });
const provider = new ethers.JsonRpcProvider(fetchReq);

stephenlacy avatar Mar 13 '23 23:03 stephenlacy

Im in the same boat, migrating a project from ethers 5.7 to 6.

previously was sending the below fetchOptions and not sure how to do this now with the new FetchRequest:

     fetchOptions: {
       mode: 'cors',
       cache: 'force-cache',
       credentials: 'same-origin',
       redirect: 'follow',
       referrer: 'client'
     }

corbanbrook avatar Feb 22 '24 20:02 corbanbrook

In v6 the defaults are used, and redirects are handled by the FetchRequest class, but it definitely makes sense to allow overriding those in the createGetUrlFunc.

I’ll mark this for the next minor patch and include a code snippet on using it.

ricmoo avatar Feb 22 '24 20:02 ricmoo

This has been added into the WIP branch for 6.14.

To use custom fetch init options, you can either:

// Modify only one request object, and its clones (such as used by JsonRpcProvider)
const request = new FetchRequest(url);
request.getUrlFunc = FetchRequest.createGetUrlFunc({ mode: "cors", ... });
const provider = new JsonRpcProvider(request);

Or:

// Modify ALL requests made by anything through FethcRequest
FetchRequest.registerGetUrl(FetchRequest.createGetUrlFunc({ mode: "cors", ... }))

The init properties method, headers, body and signal cannot be overridden, as getUrl uses these internally, but provides API means to modify these in FetchRequest.

Any feedback is welcome. :)

ricmoo avatar Jan 23 '25 00:01 ricmoo

@ricmoo Would be great if you could also export entire fetch function as well https://github.com/ethers-io/ethers.js/issues/4929.

Also, please make a look to this old issue https://github.com/ethers-io/ethers.js/pull/4686 as it sends duplicated requests on BSC ( and slow downs sending transactions )

tornadocontrib avatar Jan 24 '25 14:01 tornadocontrib