RequestInit
The RequestInit
dictionary of the Fetch API represents the set of options that can be used to configure a fetch request.
You can pass a RequestInit
object into the Request()
constructor, or directly into the fetch()
function call.
You can also construct a Request
with a RequestInit
, and pass the Request
to a fetch()
call along with another RequestInit
. If you do this, and the same option is set in both places, then the value passed directly into fetch()
is used.
Instance properties
attributionReporting
Optional Experimental-
Indicates that you want the request's response to be able to register a JavaScript-based attribution source or attribution trigger.
attributionReporting
is an object containing the following properties:eventSourceEligible
-
A boolean. If set to
true
, the request's response is eligible to register an attribution source. If set tofalse
, it isn't. triggerEligible
-
A boolean. If set to
true
, the request's response is eligible to register an attribution trigger. If set tofalse
, it isn't.
See the Attribution Reporting API for more details.
body
Optional-
The request body contains content to send to the server, for example in a
POST
orPUT
request. It is specified as an instance of any of the following types:See Setting a body for more details.
browsingTopics
Optional Experimental-
A boolean specifying that the selected topics for the current user should be sent in a
Sec-Browsing-Topics
header with the associated request.See Using the Topics API for more details.
cache
Optional-
The cache mode you want to use for the request. This may be any one of the following values:
default
-
The browser looks in its HTTP cache for a response matching the request.
- If there is a match and it is fresh, it will be returned from the cache.
- If there is a match but it is stale, the browser will make a conditional 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-store
-
The browser fetches the resource from the remote server without first looking in the cache, and will not update the cache with the downloaded resource.
reload
-
The 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-cache
-
The browser looks in its HTTP cache for a response matching the request.
- If there is a match, fresh or stale, the browser will make a conditional 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-cache
-
The 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-cached
-
The 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'smode
is"same-origin"
. Cached redirects will be followed if the request'sredirect
property is"follow"
and the redirects do not violate the"same-origin"
mode. credentials
Optional-
Controls whether or not the browser sends credentials with the request, as well as whether any
Set-Cookie
response 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:omit
-
Never send credentials in the request or include credentials in the response.
same-origin
-
Only send and include credentials for same-origin requests.
include
-
Always include credentials, even for cross-origin requests.
Including credentials in cross-origin requests can make a site vulnerable to CSRF attacks, so even if
credentials
is set toinclude
, the server must also agree to their inclusion by including theAccess-Control-Allow-Credentials
in its response. Additionally, in this situation the server must explicitly specify the client's origin in theAccess-Control-Allow-Origin
response header (that is,*
is not allowed).See Including credentials for more details.
Defaults to
same-origin
. headers
Optional-
Any headers you want to add to your request, contained within a
Headers
object 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 called Forbidden header names.
If the
mode
option is set tono-cors
, you can only set CORS-safelisted request headers.See Setting headers for more details.
integrity
Optional-
Contains the subresource integrity value of the request.
This will be checked when the resource is fetched, just as it would be when the
integrity
attribute is set on a<script>
element. The browser will compute the hash 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 the Base64-encoding of the result of hashing the resource with the specified hash algorithm.
Defaults to an empty string.
keepalive
Optional-
A 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 fetchPromise
fulfillment. It is also available in service workers.The body size for
keepalive
requests is limited to 64 kibibytes.Defaults to
false
. method
Optional-
The request method.
Defaults to
GET
. mode
Optional-
Sets cross-origin behavior for the request. One of the following values:
same-origin
-
Disallows cross-origin requests. If a
same-origin
request is sent to a different origin, the result is a network error. cors
-
If the request is cross-origin then it will use the Cross-Origin Resource Sharing (CORS) mechanism. Only CORS-safelisted response headers are exposed in the response.
no-cors
-
Disables CORS for cross-origin requests. This option comes with the following restrictions:
- The method may only be one of
HEAD
,GET
orPOST
. - The headers may only be CORS-safelisted request headers, with the additional restriction that the
Range
header is also not allowed. This also applies to any headers added by service workers. - The response is opaque, meaning that its headers and body are not available to JavaScript, and its status code is always
0
.
The main application for
no-cors
is for a service worker: although the response to ano-cors
request 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 as cache first with cache refresh). - The method may only be one of
-
Used only by HTML navigation. A
navigate
request is created only while navigating between documents.
See Making cross-origin requests for more details.
Defaults to
cors
. priority
Optional-
Specifies the priority of the fetch request relative to other requests of the same type. Must be one of the following:
high
-
A high priority fetch request relative to other requests of the same type.
low
-
A low priority fetch request relative to other requests of the same type.
auto
-
No user preference for the fetch priority. It is used if no value is set or if an invalid value is set.
Defaults to
auto
. redirect
Optional-
Determines the browser's behavior in case the server replies with a redirect status. One of the following values:
follow
-
Automatically follow redirects.
error
-
Reject the promise with a network error when a redirect status is returned.
manual
-
Return a response with almost all fields filtered out, to enable a service worker to store the response and later replay it.
Defaults to
follow
. referrer
Optional-
A string specifying the value to use for the request's
Referer
header. One of the following:- A same-origin relative or absolute URL
-
Set the
Referer
header to the given value. Relative URLs are resolved relative to the URL of the page that made the request. - An empty string
-
Omit the
Referer
header. about:client
-
Set the
Referer
header 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
. referrerPolicy
Optional-
A string that sets a policy for the
Referer
header. The syntax and semantics of this option are exactly the same as for theReferrer-Policy
header. signal
Optional-
An
AbortSignal
. If this option is set, the request can be canceled by callingabort()
on the correspondingAbortController
.
Examples
Passing options into fetch()
In this example we pass the method
, body
, and headers
options directly into the fetch()
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 the Request()
constructor
In this example we create a Request
, passing the same set of options into its constructor, and then pass the request into fetch()
:
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 both Request()
and fetch()
In this example we create a Request
, passing the method
, headers
, and body
options into its constructor. We then pass the request into fetch()
along with body
and referrer
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 Standard # requestinit |