The Fetch API is a method for retrieving data from points of presence (POPs). You can use the Fetch API to request data from POPs over HTTP or HTTPS and return the data to users. It is similar to the Fetch API in browser environments and is suitable for scenarios such as dynamic content loading, interacting with backend services, and implementing A/B testing.
Fetch API method definition
Fetch is fully asynchronous. It does not block script execution unless you use await. You can send up to four subrequests at a time. The underlying layer uses persistent connections, so you do not need to manage connection pools.
Fetch can make HTTP or HTTPS requests. Each redirect counts as one request. Each fetch request supports a maximum of 12 redirect operations.
Method definition
fetch(arg, init). For more information, see the MDN documentation for WorkerOrGlobalScope.fetch().Method limits
The Fetch API supports only domain names, not IP addresses. The default port for HTTP requests is 80, and the default port for HTTPS requests is 443.
The
credentials,referrer,referrerPolicy,cache, andintegrityproperties of theinitparameter have no effect.The default value for
redirectisfollow, which means that fetch follows 3xx responses from the origin server. To prevent fetch from following 3xx responses, setredirecttomanual.
NoteThe various Fetch modes available in a browser do not apply. For example, on CDN, DCDN, or ESA, you can use
CROS fetchto retrieve data from any origin server.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.
Gzip-compressed resources that a function retrieves using Fetch are decompressed by default. To prevent default decompression, add the
manualparameter. For more information, see the Decompress section.
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 can follow 3xx redirects. These status codes include 301, 302, 303, 307, and 308. You can specify one of the following three 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.
The redirection methods are described in the following table.
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. |
The redirect address is retrieved from the Location header. The Location header is required. If this header is missing, an error is reported.
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
If you set content-length in a fetch request, Fetch uses content-length encoding and overrides the default behavior for sending the body. If you do not set content-length, Fetch reads and sends all data from the body stream using chunked encoding.
content-lengthsettingsIf
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 automatically decompresses content. After decompression, the
content-lengthheader in the response still exists. Thiscontent-lengthindicates the data size before decompression. If you modify the body before using Fetch, pay attention tocontent-length. Otherwise, the sent content may be incorrect.In the following example, assume a client sends a POST request that includes the
content-lengthheader. If you create a new request using Fetch and reuse the header object from the client request, thecontent-lengthvalue may be inconsistent with the actual size of the body being sent. When you pass headers through, always verify whether the actual body size has changed.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
For more information, see the MDN documentation for Request.
Limits
The following properties of the Request object are not implemented and do not apply in the CDN, DCDN, or ESA context.
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().
The Request interface is an extension of the standard. It lets you ignore the request body while ensuring the body stream is fully read from the underlying socket. The body is not read into the memory of the JavaScript virtual machine, which avoids garbage collection (GC) delays. If you do not need to read the body of a Fetch request, call
request.ignore. For example,await request.ignore(). This improves performance because the runtime automatically returns the connection to the connection pool for reuse after the body is fully read.
Response
Definition
For more information, see the MDN documentation for Response.
Limits
The useFinalURLS and error properties of the Response object are not implemented and do not apply in the CDN, DCDN, or ESA context.
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 a list of all redirect URLs (non-standard):
response.urlList. The Response object implements a body mixin, similar to the Request object. You can use similar methods to retrieve the body object.
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.