Fetch
The
Fetch API is designed based on the standard Web API Fetch. You can add fetch to the edge function runtime to initiate an async request to fetch remote.Overview
function fetch(request: string | Request, requestInit?: RequestInit): Promise<Response>
Parameters
Parameter Name | Type | Required | Description |
Request | string | Request | Yes | Specifies the request resource to be obtained. |
requestInit | No |
Advanced Features
With
fetch, you can pass in specific parameters for finer configuration of EdgeOne node caching, fetching from the origin, image processing and redirection.Accessing EdgeOne Node Cache or Origin-Pull
When a client request comes to a domain name domain name connected to EdgeOne (such as www.example.com), if the request triggers an edge function,
fetch(www.example.com) is executed in the edge function. The request is directed to the cache on the EdgeOne node. If no cache is hit, the request is redirected to the origin.Restrictions and requirements:
To access the EdgeOne node cache and origin-pull with
fetch, the following conditions must be met:1. A client accesses the acceleration domain name of a site onboarded to EdgeOne, and the request triggers the execution of an edge function.
2. The HOST in
request.url specified by fetch(request) is the same as the HOST in the client request URL.3. Host of
request.headers.host specified in fetch(request) is the same as the HOST of client request URL.If the above conditions are not met,
fetch will perform origin-pull over the public network.Use
fetch(event.request) to obtain the cache from EdgeOne nodes and pull resources from the origin if no cache is hit.addEventListener('fetch', (event) => {// fetch(event.request) obtains the EdgeOne CDN cache and origin-pull.const response = fetch(event.request);event.respondWith(response);});
Use
fetch(url) to obtain the cache from EdgeOne nodes and pull resources from the origin if no cache is hit.addEventListener('fetch', (event) => {event.respondWith(handleEvent(event));});async function handleEvent(event) {const { request } = event;const urlInfo = new URL(request.url);// Origin-pull URL rewriteconst url = `${urlInfo.origin}/h5${urlInfo.pathname}`;// fetch(url) obtains the EdgeOne CDN cache and origin-pull.const response = await fetch(url);return response;}
Image Processing
You can use
requestInit.eo.image to scale images or convert the image format. For details, see ImageProperties.Note:
To implement Image Processing with
fetch(request, requestInit), the conditions for fetch to obtain the EdgeOne node cache and origin-pull must also be met.Timeout Settings
fetch supports configuring the request timeout using requestInit.eo.timeoutSetting.The default timeout for establishing a connection is 3 seconds, the default timeout for reading the response is 15 seconds, and the default timeout for sending the request is 300 seconds. The maximum value that can be set is 300 seconds. If the connection establishment times out, a net_exception_connect_timeout exception is thrown; if reading the response or sending the request times out, a net_exception_timeout exception is thrown.fetch(url, {eo: {timeoutSetting: {connectTimeout: 60000, // Timeout for establishing a connection, in milliseconds. Default value: 3000.readTimeout: 60000, // Timeout for reading the response, in milliseconds. Default value: 15000.writeTimeout: 60000, // Timeout for sending the request, in milliseconds. Default value: 300000.}}})
Redirection
fetch supports 3xx redirect status codes. You can use the second parameter requestInit.redirect to specify the redirect status code. For more information, see RequestInit.The default behavior of
fetch is to automatically follow redirects, which means the default value of the requestInit.redirect property in the second parameter is follow. This may cause issues in the following scenarios:1. Login/Authentication scenario: The origin server sets the
Set-Cookie header in a redirect response (for example, it returns 302 and sets a session Cookie after a successful login). Automatically following redirects prevents the Cookie from being correctly delivered to the client.2. Relative path resource loading: The origin server redirects the homepage to a subdirectory (for example,
/ is redirected to /subdir/index.html). If resources such as CSS/JS on the page use relative paths, automatically following redirects causes the client to load resources based on the original path, which may result in incorrect paths.3. Custom redirect logic required: You need to perform specific operations before and after redirects (such as logging and modifying redirect targets).
If your business involves the above scenarios, set the
redirect parameter to manual. Edge Functions will directly return the redirect response to the client, and the client will perform the redirect.const response = await fetch(url, { redirect: 'manual' });
Redirect rules conform to the Fetch Standard. The follow rules vary based on the status code.
Status Code | Redirection Rules |
301,302 | The POST method is converted to the GET method. |
303 | All methods except HEAD/GET are converted to the GET method. |
307,308 | Preserve the original method. |
Important
The redirect address is obtained from the
Location response header. If Location does not exist, no redirect action is taken.The value of the
Location can be an absolute URL or a relative URL. For more information, see RFC-3986: URI Reference.Runtime Limitations
If you use
fetch to initiate a request in an edge function, take note of the following limits:Number of times: Each time an edge function runs,
fetch can be initiated for a maximum of 64 times. If the limit is exceeded, the exceeding requests fail and exceptions are returned.Number of concurrencies: Each time an edge function runs,
fetch can be initiated at a maximum concurrency of 8. If the limit is exceeded, the exceeding requests are postponed until a running fetch is resolved.Timeout limits: When
fetch is used in edge functions, the default timeout for establishing a connection is 3 seconds, the default timeout for reading a response is 15 seconds, and the default timeout for sending a request is 300 seconds, with a maximum configurable value of 300 seconds.Note
Each redirect is counted as a request and has a higher priority than newly-initiated
fetch requests.References