RequestInit
TheRequestInit dictionary of theFetch API represents the set of options that can be used to configure afetch request.
You can pass aRequestInit object into theRequest() constructor, or directly into thefetch() function call.
You can also construct aRequest with aRequestInit, and pass theRequest to afetch() call along with anotherRequestInit. If you do this, and the same option is set in both places, then the value passed directly intofetch() is used.
In this article
Instance properties
attributionReportingOptionalExperimentalIndicates that you want the request's response to be able to register a JavaScript-basedattribution source orattribution trigger.
attributionReportingis an object containing the following properties:eventSourceEligibleA boolean. If set to
true, the request's response is eligible to register an attribution source. If set tofalse, it isn't.triggerEligibleA boolean. If set to
true, the request's response is eligible to register an attribution trigger. If set tofalse, it isn't.
See theAttribution Reporting API for more details.
bodyOptionalThe request body contains content to send to the server, for example in a
POSTorPUTrequest. It is specified as an instance of any of the following types:SeeSetting a body for more details.
browsingTopicsOptionalExperimentalA boolean specifying that the selected topics for the current user should be sent in a
Sec-Browsing-Topicsheader with the associated request.SeeUsing the Topics API for more details.
cacheOptionalThecache mode you want to use for the request. This may be any one of the following values:
defaultThe browser looks in its HTTP cache for a response matching the request.
- If there is a match and it isfresh, it will be returned from the cache.
- If there is a match but it isstale, the browser will make aconditional request to the remote server. If the server indicates that the resource has not changed, it will be returned from the cache. Otherwise the resource will be downloaded from the server and the cache will be updated.
- If there is no match, the browser will make a normal request, and will update the cache with the downloaded resource.
no-storeThe browser fetches the resource from the remote server without first looking in the cache,and will not update the cache with the downloaded resource.
reloadThe browser fetches the resource from the remote server without first looking in the cache,but then will update the cache with the downloaded resource.
no-cacheThe browser looks in its HTTP cache for a response matching the request.
- If there is a match,fresh or stale, the browser will make aconditional request to the remote server. If the server indicates that the resource has not changed, it will be returned from the cache. Otherwise the resource will be downloaded from the server and the cache will be updated.
- If there is no match, the browser will make a normal request, and will update the cache with the downloaded resource.
force-cacheThe browser looks in its HTTP cache for a response matching the request.
- If there is a match,fresh or stale, it will be returned from the cache.
- If there is no match, the browser will make a normal request, and will update the cache with the downloaded resource.
only-if-cachedThe browser looks in its HTTP cache for a response matching the request.Experimental
- If there is a match,fresh or stale, it will be returned from the cache.
- If there is no match, a network error is returned.
The
"only-if-cached"mode can only be used if the request'smodeis"same-origin". Cached redirects will be followed if the request'sredirectproperty is"follow"and the redirects do not violate the"same-origin"mode.credentialsOptionalControls whether or not the browser sends credentials with the request, as well as whether any
Set-Cookieresponse headers are respected. Credentials are cookies,TLS client certificates, or authentication headers containing a username and password. This option may be any one of the following values:omitNever send credentials in the request or include credentials in the response.
same-originOnly send and include credentials for same-origin requests.
includeAlways include credentials, even for cross-origin requests.
Including credentials in cross-origin requests can make a site vulnerable toCSRF attacks, so even if
credentialsis set toinclude, the server must also agree to their inclusion by including theAccess-Control-Allow-Credentialsin its response. Additionally, in this situation the server must explicitly specify the client's origin in theAccess-Control-Allow-Originresponse header (that is,*is not allowed).SeeIncluding credentials for more details.
Defaults to
same-origin.duplexOptionalExperimentalControls duplex behavior of the request. If this is present it must have the value
half, meaning that the browser must send the entire request before processing the response.This option must be present when
bodyis aReadableStream.headersOptionalAny headers you want to add to your request, containedwithin a
Headersobject or an object literal whose keys are the names of headers and whose values are the header values.Many headers are set automatically by the browser and can't be set by a script: these are calledForbidden request headers.
If the
modeoption is set tono-cors, you can only setCORS-safelisted request headers.SeeSetting headers for more details.
integrityOptionalContains thesubresource integrityvalue of the request.
This will be checked when the resource is fetched, just as it would be when the
integrityattribute is set on a<script>element. The browser will compute thehash of the fetched resource using the specified algorithm, and if the result does not match the value specified, the browser will reject the fetch request with a network error.The format of this option is
<hash-algo>-<hash-source>where:<hash-algo>is one of the following values:sha256,sha384, orsha512<hash-source>is theBase64-encoding of the result of hashing the resource with the specified hash algorithm.
Defaults to an empty string.
keepaliveOptionalA boolean.When set to
true, the browser will not abort the associated request if the page that initiated it is unloaded before the request is complete.This enables afetch()request to send analytics at the end of a session even if the user navigates away from or closes the page.This has some advantages over using
Navigator.sendBeacon()for the same purpose.For example, you can use HTTP methods other thanPOST, customize request properties, and access the server response via the fetchPromisefulfillment.It is also available inservice workers.The body size for
keepaliverequests is limited to 64 kibibytes.Defaults to
false.methodOptionalTherequest method.
Defaults to
GET.modeOptionalSets cross-origin behavior for the request. One of the following values:
same-originDisallows cross-origin requests. If a
same-originrequest is sent to a different origin, the result is a network error.corsIf the request is cross-origin then it will use theCross-Origin Resource Sharing (CORS) mechanism. OnlyCORS-safelisted response headers are exposed in the response.
no-corsDisables CORS for cross-origin requests. This option comes with the following restrictions:
- The method may only be one of
HEAD,GETorPOST. - The headers may only beCORS-safelisted request headers, with the additional restriction that the
Rangeheader is also not allowed. This also applies to any headers added by service workers. - The response isopaque, meaning that its headers and body are not available to JavaScript, and itsstatus code is always
0.
The main application for
no-corsis for a service worker: although the response to ano-corsrequest can't be read by JavaScript, it can be cached by a service worker and then used as a response to an intercepted fetch request. Note that in this situation you don't know whether the request succeeded or not, so you should adopt a caching strategy which enables the cached response to be updated from the network (such ascache first with cache refresh).- The method may only be one of
navigateUsed only by HTML navigation. A
navigaterequest is created only while navigating between documents.
SeeMaking cross-origin requests for more details.
Defaults to
cors.priorityOptionalSpecifies the priority of the fetch request relative to other requests of the same type. Must be one of the following:
highA high priority fetch request relative to other requests of the same type.
lowA low priority fetch request relative to other requests of the same type.
autoNo user preference for the fetch priority.It is used if no value is set or if an invalid value is set.
Defaults to
auto.redirectOptionalDetermines the browser's behavior in case the server replies with aredirect status. One of the following values:
followAutomatically follow redirects.
errorReject the promise with a network error when a redirect status is returned.
manualReturn a response with almost all fields filtered out, to enable a service worker to store the response and later replay it.
Defaults to
follow.referrerOptionalA string specifying the value to use for the request's
Refererheader. One of the following:- A same-origin relative or absolute URL
Set the
Refererheader to the given value. Relative URLs are resolved relative to the URL of the page that made the request.- An empty string
Omit the
Refererheader.about:clientSet the
Refererheader to the default value for the context of the request (for example, the URL of the page that made the request).
Defaults to
about:client.referrerPolicyOptionalA string that sets a policy for the
Refererheader. The syntax and semantics of this option are exactly the same as for theReferrer-Policyheader.signalOptionalAn
AbortSignal. If this option is set, the request can be canceled by callingabort()on the correspondingAbortController.
Examples
>Passing options intofetch()
In this example we pass themethod,body, andheaders options directly into thefetch() method call:
async function post() { const response = await fetch("https://example.org/post", { method: "POST", body: JSON.stringify({ username: "example" }), headers: { "Content-Type": "application/json", }, }); console.log(response.status);}Passing options into theRequest() constructor
In this example we create aRequest, passing the same set of options into its constructor, and then pass the request intofetch():
async function post() { const request = new Request("https://example.org/post", { method: "POST", body: JSON.stringify({ username: "example" }), headers: { "Content-Type": "application/json", }, }); const response = await fetch(request); console.log(response.status);}Passing options into bothRequest() andfetch()
In this example we create aRequest, passing themethod,headers, andbody options into its constructor. We then pass the request intofetch() along withbody andreferrer options:
async function post() { const request = new Request("https://example.org/post", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ username: "example1" }), }); const response = await fetch(request, { body: JSON.stringify({ username: "example2" }), referrer: "", }); console.log(response.status);}In this case the request will be sent with the following options:
method: "POST"headers: {"Content-Type": "application/json"}body: '{"username":"example2"}'referrer: ""
Specifications
| Specification |
|---|
| Fetch> # requestinit> |