Proxied fetch - Docs ↗

The Javascript Fetch API is directly available within a Val. However, the requests sent using this API are not proxied or retried. This is problematic in some use cases where requests may be blocked by the receiving server for using particular IP addresses. Additionally, network blips or unreliable web services may lead to failed Vals if not handled properly.

The Val Town standard library contains an alternative version, std/fetch, that wraps the Javascript Fetch API to provide additional functionality. The fetch function from std/fetch reroutes requests using a proxy vendor so that requests obtain different IP addresses. It also automatically retries failed requests several times. Note that using std/fetch may be significantly slower than directly calling the Javascript Fetch API due to extra network hops.

Usage

After importing std/fetch, the fetch method is used with the same signature as the Javascript Fetch API.

Create valimport { fetch } from "https://esm.town/v/std/fetch"; let result = await fetch("https://api64.ipify.org?format=json"); let json = await result.json(); console.log(json.ip);

If you run the above code multiple times, you'll see that it returns different IP addresses, because std/fetch uses proxies so that each request is made from a different IP address.

Readme
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { API_URL } from "https://esm.town/v/std/API_URL";
import { rawFetch } from "https://esm.town/v/std/rawFetch";
/**
* Wraps the JavaScript Fetch function to anonymize where the request is
* coming from ([Docs ↗](https://docs.val.town/std/fetch))
*
* @param {string | URL} input - The URL to fetch
* @param {RequestInit} [requestInit] - Optional configuration data (HTTP
* method, headers, etc) ([Docs ↗](https://deno.land/api@v1.42.1?s=RequestInit))
*/
export async function fetch(input: string | URL, requestInit?: RequestInit) {
let query = new URLSearchParams({
url: input.toString(),
});
return rawFetch(`${API_URL}/v1/fetch?${query}`, {
...requestInit,
headers: {
"X-Valtown-Authorization": `Bearer ${Deno.env.get("valtown")}`,
...requestInit?.headers ?? {},
},
});
}
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.
v5 was merged from the PR "Update JSDocs" by andreterron