fetch()
The global fetch() method starts the process of fetching a
resource from the network, returning a promise which is fulfilled once the response is
available.
The promise resolves to the Response object
representing the response to your request.
A fetch() promise only rejects when a
network error is encountered (which is usually when there's a permissions issue or
similar). A fetch() promise does
not reject on HTTP errors (404, etc.). Instead, a
then() handler must check the Response.ok and/or
Response.status properties.
Note: The
fetch()method's parameters are identical to those of theRequest()constructor.
Explicit Backends
Internally, Fastly uses named backends to handle fetch requests, which need to be explicitly defined to enable custom HTTP origins to be fetched by the service.
This backend option is then a special Fastly-specific fetch option that is provided to the fetch() call:
fetch('https://origin.com/path', { backend: 'origin' });
Backends are configured using the Fastly service backend configuration, see the Backend documentation for more information.
Dynamic Backends
Dynamic backends are a compute feature that allow services to define backends for themselves. This is a service-level Fastly feature that must be enabled through Fastly Support.
When dynamic backends are enabled at the service level, the explicit backend option is no longer required for fetch() requests, and will instead be automatically created.
In addition, custom backend configuration options can then also be provided through the Backend() constructor.
Syntax
fetch(resource)
fetch(resource, options)
Parameters
resource: This defines the resource that you wish to fetch. This can either be:
- A string or any other object with a "toString" method.
- A
Requestobject.
optionsoptional: An object containing any custom settings that you want to apply to the request. The possible options are:
method- : The request method, e.g.,
GET,POST.
- : The request method, e.g.,
headers- : Any headers you want to add to your request, contained within a
Headersobject or an object literal withStringvalues.
- : Any headers you want to add to your request, contained within a
body- : Any body that you want to add to your request: this can be an
ArrayBuffer, aTypedArray, aDataView, aURLSearchParams, string object or literal, or aReadableStreamobject.
- : Any body that you want to add to your request: this can be an
backendFastly-specific- Fastly-specific
cacheOverrideFastly-specificcacheKeyFastly-specificfastlyFastly-specificdecompressGzip: boolean optional- Whether to automatically gzip decompress the Response or not.
Return value
A Promise that resolves to a Response object.