Fetch data from edge POPs over HTTP or HTTPS. The Fetch API works like the browser Fetch API and supports dynamic content loading, backend interaction, and A/B testing.
Method definition
Fetch is fully asynchronous and does not block script execution unless you use await. Up to four concurrent subrequests are supported. Persistent connections are managed internally.
Fetch supports HTTP and HTTPS requests. Each redirect counts as one subrequest, with a maximum of 12 redirect operations per request.
-
Method definition
fetch(arg, init). The method follows the MDN WorkerOrGlobalScope.fetch() specification. -
Method limits
-
The Fetch API supports domain names only, not IP addresses. Default ports: 80 (HTTP), 443 (HTTPS).
-
The
credentials,referrer,referrerPolicy,cache, andintegrityproperties of theinitparameter have no effect. -
redirectdefaults tofollow, which follows 3xx responses from the origin. Setredirecttomanualto disable redirect following.
Note-
Browser-specific Fetch modes do not apply. On CDN, DCDN, or ESA,
CROS fetchcan retrieve data from any origin. -
To send four or more subrequests, submit a ticket to request a quota increase.
-
The total length of a request URL cannot exceed 4 KB.
-
Fetched gzip-compressed resources are decompressed by default. Add the
manualparameter to disable decompression. The Decompress section covers details.
-
-
Set a timeout period
-
Timeout function
/** * Request timeout control implementation * * @param {Number} timeout Timeout period, in ms * @param {Object} config Timeout configuration * - @param {Object|Funtion} handler Value to return on timeout * @returns */ const RequestTimeout = (timeout, config) => { return new Promise((resolve) => { const { handler = null } = config; let timer = setTimeout(() => { clearTimeout(timer); timer = null; const defaultRes = (typeof handler === 'function' ? handler() : handler) || {}; resolve(defaultRes); }, timeout); }); }; -
Example call
const KV_TIMEOUT = 1000; let edgekv = new EdgeKV({ namespace: KV_NS, }); let kvRequest = edgekv.get(key, getType); let timeoutPromise = RequestTimeout(KV_TIMEOUT, { handler: { res: {}, errorMessage: `kv request timeout (${KV_TIMEOUT}ms)`, } }); let resp = await Promise.race([ kvRequest, timeoutPromise, ]); if (resp === undefined) { return "kv not found, key = " + key; } else { return resp; }
-
Redirect
Fetch follows 3xx redirects (301, 302, 303, 307, 308). Specify one of three redirect behaviors:
-
{redirect: "manual"}: Does not follow 3xx redirects. You must handle the redirects manually. -
{redirect: "error"}: An error is thrown for 3xx responses. -
{redirect: "follow"}: (Default) Follows 3xx redirects. A maximum of 20 redirects can be followed.
Redirect behavior by status code:
|
Status code |
Redirection details |
|
301, 302, 303, 308 |
The request method is changed to GET, and the body is ignored. |
|
307 |
Only GET methods are followed. An error is reported for other methods. |
Redirects use the Location header, which is required. A missing Location header causes an error.
-
The
Locationheader can contain a list of URLs separated by commas (,). Only the first URL is used, and the others are ignored. -
The
Locationheader can contain an absolute URL or a relative URL.
Decompress
The Fetch API allows you to configure a decompression mode, such as fetch("https://www.example.com",{decompress: "manual"}). The decompress parameter supports the following values:
-
manual: does not decompress data. If the server returns compressed data upon a fetch request, the data received by EdgeRoutine (ER) is also compressed.
-
decompress: automatically decompresses data. This is the default value. The Fetch API supports Gzip compression. ER automatically detects or decompresses data based on the Content-Encoding header. After ER decompresses data, ER changes the value of Content-Encoding. If the Gzip parameter is deleted, you can configure the following settings to prevent exceptions during data transmission:
-
content-encoding: gzip: ER recognizes the value of Content-Encoding and decompresses data. -
content-encoding: gzip, identity: ER recognizes the value of Content-Encoding and decompresses data.
NoteAlgorithms other than Gzip cause exceptions.
-
-
fallbackIdentity: The effect of this value is similar to the effect of the value decompress. If ER cannot recognize this value, ER does not decompress data.
After the Fetch API automatically decompresses data, you cannot pass the Content-Length header as needed if the response contains the Content-Length header. This is because the Content-Length header indicates the size of the data before decompression.
content-length
When content-length is set, Fetch sends the body using content-length encoding. Without content-length, Fetch sends all body data using chunked encoding.
-
content-lengthsettings-
If
content-lengthis a non-negative number: Fetch reads and sends the specified number of bytes from the body stream. The data is sent usingcontent-lengthencoding. Ifcontent-lengthis 0, no data is sent. -
If
content-lengthis an invalid value: Fetch sends all data in the body using chunked encoding.
-
-
Example
Fetch decompresses content automatically. The response
content-lengthheader still reflects the pre-decompression size. If you modify the body before forwarding, verify thatcontent-lengthmatches the actual body size. A mismatch incontent-lengthcauses incorrect content delivery.In this example, a client sends a POST request with a
content-lengthheader. If you create a new Fetch request reusing the client headers, thecontent-lengthmay not match the new body size. Always verify body size when passing headers through.export default { fetch(request) { return handleRequest(request) } } async function handleRequest(request) { return fetch("http://www.example.com", { headers: request.headers, method: request.method, body: "SomeData" }); }
Headers
-
Definition
For more information about the Headers object, see Headers.
-
Limits
A header records the amount of memory resources that are consumed. The maximum size of a Headers object is 8 KB. If the size of a Headers object exceeds this limit, a JavaScript exception is thrown.
-
Blacklist
The Fetch API uses a header blacklist. If you attempt to read or write a header that is in the blacklist, an exception is thrown. The following table describes the headers that are included in the blacklist.
-
expect
-
te
-
trailer
-
upgrade
-
proxy-connection
-
connection
-
keep-alive
-
dnt
-
host
-
Reserved headers
-
Request
-
Definition
Follows the MDN Request specification.
-
Limits
The following Request properties are not supported in CDN, DCDN, or ESA.
-
context
-
credentials
-
destination
-
integrity
-
mode
-
referrer
-
referrerPolicy
-
cache
-
-
Common uses
-
Retrieve the request method:
request.method. -
Retrieve the request URL:
request.url. -
Retrieve the request headers:
request.headers. -
Retrieve the request payload:
request.body. The body is a ReadableStream object. -
Retrieve JSON:
await request.json(). -
Retrieve form data:
await request.formData(). -
Retrieve a UTF-8 string:
await request.text().
As a non-standard extension,
request.ignoredrains the body stream at the socket level without loading it into JavaScript VM memory, avoiding GC delays. Callawait request.ignore()when you do not need the request body. The runtime returns the connection to the pool after the body is fully read. -
Response
-
Definition
Follows the MDN Response specification.
-
Limits
The useFinalURLS and error properties are not supported in CDN, DCDN, or ESA.
-
Common uses
-
Retrieve the response code:
response.status. -
Retrieve the response reason phrase:
response.statusText. -
Retrieve the response headers:
response.headers. -
Retrieve the response URL:
response.url. This is the final URL after all redirects. -
Retrieve all redirect URLs (non-standard):
response.urlList. Response implements a body mixin like Request, so the same body-retrieval methods apply.
-
FormData
-
Definition
For more information about the FormData operation, see FormData.
-
Limits
The FormData operation is similar to the Headers operation. FormData limits the size of headers. If the size of a header exceeds the upper limit, an exception is thrown. If you send FormData as an HTTP request body,
content-typeis set toform-data/multipartby default.
URLSearchParams
-
Definition
For more information about the URLSearchParams operation, see URLSearchParams().
-
Limits
If you send URLSearchParams as an HTTP request body,
content-typeis set toapplication/x-www-form-urlencodeby default. The data size cannot exceed 1,000 bytes.
Blob and File
-
Definition
-
Limits
ER supports the Blob and File classes, which meet the standards of the Blob and File operations. ER cannot read or write files. You can pass the Blob and File classes supported by ER to the response body. The value of the
content-typeheader is the same as the MIME type in theBloborFileoperation.