Skip to content
This repository was archived by the owner on Oct 16, 2025. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ interface Request {
method: string;
headers: Record<string, string>;
body: string;
credentials?: 'include' | 'omit' | 'same-origin';
}
interface FetchConfig {
fetchUrl: string;
Expand All @@ -33,6 +34,7 @@ interface FetchConfig {
interface FetchMiddlewareOptions {
rpcUrl: string;
originHttpHeaderKey?: string;
sendCredentials?: boolean;
}

interface FetchMiddlewareFromReqOptions extends FetchMiddlewareOptions {
Expand All @@ -42,12 +44,14 @@ interface FetchMiddlewareFromReqOptions extends FetchMiddlewareOptions {
export function createFetchMiddleware({
rpcUrl,
originHttpHeaderKey,
sendCredentials,
}: FetchMiddlewareOptions): JsonRpcMiddleware<string[], Block> {
return createAsyncMiddleware(async (req, res, _next) => {
const { fetchUrl, fetchParams } = createFetchConfigFromReq({
req,
rpcUrl,
originHttpHeaderKey,
sendCredentials,
});

// attempt request multiple times
Expand Down Expand Up @@ -129,6 +133,7 @@ export function createFetchConfigFromReq({
req,
rpcUrl,
originHttpHeaderKey,
sendCredentials,
}: FetchMiddlewareFromReqOptions): FetchConfig {
const parsedUrl: URL = new URL(rpcUrl);
const fetchUrl: string = normalizeUrlFromParsed(parsedUrl);
Expand Down Expand Up @@ -170,6 +175,10 @@ export function createFetchConfigFromReq({
fetchParams.headers[originHttpHeaderKey] = originDomain;
}

if (sendCredentials === true) {
fetchParams.credentials = 'include';
}

return { fetchUrl, fetchParams };
}

Expand Down
25 changes: 25 additions & 0 deletions test/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,31 @@ test('fetch - origin header', (t) => {
t.end();
});

test('fetch - send credentials', (t) => {
const req = {
method: 'eth_getBlockByNumber',
params: ['0x482103', true],
};
const rpcUrl = 'http://www.xyz.io/rabbit:3456?id=100';
const { fetchUrl, fetchParams } = createFetchConfigFromReq({
req,
rpcUrl,
sendCredentials: true,
});

t.equals(fetchUrl, rpcUrl);
t.deepEquals(fetchParams, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(req),
credentials: 'include',
});
t.end();
});

test('fetch - auth in url', (t) => {
const req = {
method: 'eth_getBlockByNumber',
Expand Down