Request
The Request
interface represents an HTTP request, and is part of the Fetch API.
Background
The most common way you’ll encounter a Request
object is as a property of an incoming FetchEvent
.
addEventListener("fetch", event => { let request = event.request // Request object
// ...})
You may also want to construct a Request
yourself when you need to modify a request object, because a FetchEvent
’s request
property is immutable.
addEventListener("fetch", event => { const request = event.request const url = "https://example.com"
const modifiedRequest = new Request(url, { body: request.body, headers: request.headers, method: request.method, redirect: request.redirect })
// ...})
The global fetch
method itself invokes the Request
constructor, thus the RequestInit
and RequestInitCfProperties
types defined below also describe the valid parameters that can be passed to fetch
.
Constructor
let request = new Request(input [, init])
Parameters
input
string | Request
- Either a string that contains a URL, or an existing
Request
object.
- Either a string that contains a URL, or an existing
init
RequestInit
- Optional options object that contains settings to apply to the
Request
.
- Optional options object that contains settings to apply to the
RequestInit
- Cloudflare-specific properties that can be set on the
Request
that control how Cloudflare’s edge handles the request.
- Cloudflare-specific properties that can be set on the
method
string
- The HTTP request method. The default is
GET
.
- The HTTP request method. The default is
headers
Headers
body
string | ReadableStream | FormData | URLSearchParams
- The request body, if any.
redirect
string
- The redirect mode to use:
follow
,error
, ormanual
. The default for a newRequest
object isfollow
. Note, however, that the incomingRequest
property of aFetchEvent
will have redirect modemanual
.
- The redirect mode to use:
RequestInitCfProperties
An object containing Cloudflare-specific properties that can be set on the Request
object. For example:
// Disable ScrapeShield for this request.fetch(event.request, { cf: { scrapeShield: false } })
Invalid or incorrectly-named keys in the cf
object will be silently ignored. Consider using TypeScript and @cloudflare/workers-types
to ensure proper use of the cf
object.
apps
boolean
- Whether Cloudflare Apps should be enabled for this request. Defaults to
true
.
- Whether Cloudflare Apps should be enabled for this request. Defaults to
cacheEverything
boolean
- This option forces Cloudflare to cache the response for this request, regardless of what headers are seen on the response. This is equivalent to setting the page rule “Cache Level” (to “Cache Everything”). Defaults to
false
.
- This option forces Cloudflare to cache the response for this request, regardless of what headers are seen on the response. This is equivalent to setting the page rule “Cache Level” (to “Cache Everything”). Defaults to
cacheKey
string
- A request’s cache key is what determines if two requests are “the same” for caching purposes. If a request has the same cache key as some previous request, then we can serve the same cached response for both.
cacheTtl
number
- This option forces Cloudflare to cache the response for this request, regardless of what headers are seen on the response. This is equivalent to setting two page rules: “Edge Cache TTL” and “Cache Level” (to “Cache Everything”).
cacheTtlByStatus
{ [key: string]: number }
- This option is a version of the
cacheTtl
feature which chooses a TTL based on the response’s status code. If the response to this request has a status code that matches, Cloudflare will cache for the instructed time, and override cache instructives sent by the origin. For example:{ "200-299": 86400, 404: 1, "500-599": 0 }
.
- This option is a version of the
minify
{ javascript?: boolean; css?: boolean; html?: boolean; }
- Enables or disables AutoMinify for various file types. For example:
{ javascript: true, css: true, html: false }
.
- Enables or disables AutoMinify for various file types. For example:
mirage
boolean
- Whether Mirage should be enabled for this request, if otherwise configured for this zone. Defaults to
true
.
- Whether Mirage should be enabled for this request, if otherwise configured for this zone. Defaults to
polish
string
- Sets Polish mode. The possible values are
lossy
,lossless
oroff
.
- Sets Polish mode. The possible values are
resolveOverride
string
- Directs the request to an alternate origin server by overriding the DNS lookup. The value of
resolveOverride
specifies an alternate hostname which will be used when determining the origin IP address, instead of using the hostname specified in the URL. TheHost
header of the request will still match what is in the URL. Thus,resolveOverride
allows a request to be sent to a different server than the URL /Host
header specifies. However,resolveOverride
will only take effect if both the URL host and the host specified byresolveOverride
are within your zone. If either specifies a host from a different zone / domain, then the option will be ignored for security reasons. If you need to direct a request to a host outside your zone (while keeping theHost
header pointing within your zone), first create a CNAME record within your zone pointing to the outside host, and then setresolveOverride
to point at the CNAME record. Note that, for security reasons, it is not possible to set theHost
header to specify a host outside of your zone unless the request is actually being sent to that host.
- Directs the request to an alternate origin server by overriding the DNS lookup. The value of
scrapeShield
boolean
- Whether ScrapeShield should be enabled for this request, if otherwise configured for this zone. Defaults to
true
.
- Whether ScrapeShield should be enabled for this request, if otherwise configured for this zone. Defaults to
Properties
All properties of an incoming Request
object (i.e. event.request
) are read only. To modify a request, you must create a new Request
object and pass the options to modify to its constructor.
body
ReadableStream
- Stream of the body contents.
bodyUsed
Boolean
- Declares whether the body has been used in a response yet.
cf
IncomingRequestCfProperties
- An object containing properties about the incoming request provided by Cloudflare’s edge network.
headers
Headers
method
string
- Contains the request’s method, e.g.
GET
,POST
, etc.
- Contains the request’s method, e.g.
redirect
string
- Contains the mode for how redirects are handled. It may be one of
follow
,error
, ormanual
.
- Contains the mode for how redirects are handled. It may be one of
url
string
- Contains the URL of the request.
IncomingRequestCfProperties
In addition to the properties on the standard Request
object, the request.cf
object on an inbound Request
contains information about the request provided by Cloudflare’s edge.
All plans have access to:
asn
string
- ASN of the incoming request, e.g.
395747
.
- ASN of the incoming request, e.g.
colo
string
- The three-letter airport code of the data center that the request hit, e.g.
"DFW"
.
- The three-letter airport code of the data center that the request hit, e.g.
country
string | null
- Country of the incoming request. The two-letter country code in the request. This is the same value as that provided in the
CF-IPCountry
header, e.g."US"
.
- Country of the incoming request. The two-letter country code in the request. This is the same value as that provided in the
httpProtocol
string
- HTTP Protocol, e.g.
"HTTP/2"
.
- HTTP Protocol, e.g.
requestPriority
string | null
- The browser-requested prioritization information in the request object, e.g.
"weight=192;exclusive=0;group=3;group-weight=127"
.
- The browser-requested prioritization information in the request object, e.g.
tlsCipher
string
- The cipher for the connection to Cloudflare, e.g.
"AEAD-AES128-GCM-SHA256"
.
- The cipher for the connection to Cloudflare, e.g.
tlsClientAuth
Object | null
- Only set when using Cloudflare Access. Object with the following properties:
certIssuerDNLegacy
,certIssuerDN
,certIssuerDNRFC2253
,certSubjectDNLegacy
,certVerified
,certNotAfter
,certSubjectDN
,certFingerprintSHA1
,certNotBefore
,certSerial
,certPresented
,certSubjectDNRFC2253
.
- Only set when using Cloudflare Access. Object with the following properties:
tlsVersion
string
- The TLS version of the connection to Cloudflare, e.g.
TLSv1.3
.
- The TLS version of the connection to Cloudflare, e.g.
Business and Enterprise scripts have access to:
city
string | null
- City of the incoming request, e.g.
"Austin"
.
- City of the incoming request, e.g.
continent
string | null
- Continent of the incoming request, e.g.
"NA"
.
- Continent of the incoming request, e.g.
latitude
string | null
- Latitude of the incoming request, e.g.
"30.27130"
.
- Latitude of the incoming request, e.g.
longitude
string | null
- Longitude of the incoming request, e.g.
"-97.74260"
.
- Longitude of the incoming request, e.g.
postalCode
string | null
- Postal code of the incoming request, e.g.
"78701"
.
- Postal code of the incoming request, e.g.
metroCode
string | null
- Metro code (DMA) of the incoming request, e.g.
"635"
.
- Metro code (DMA) of the incoming request, e.g.
region
string | null
- If known, the ISO 3166-2 name for the first level region associated with the IP address of the incoming request, e.g.
"Texas"
.
- If known, the ISO 3166-2 name for the first level region associated with the IP address of the incoming request, e.g.
regionCode
string | null
- If known, the ISO 3166-2 code for the first level region associated with the IP address of the incoming request, e.g.
"TX"
.
- If known, the ISO 3166-2 code for the first level region associated with the IP address of the incoming request, e.g.
timezone
string
- Timezone of the incoming request, e.g.
"America/Chicago"
.
- Timezone of the incoming request, e.g.
Methods
Instance methods
These methods are only available on an instance of a Request
object or through its prototype.
clone()
Promise<Request>
- Creates a copy of the
Request
object.
- Creates a copy of the
arrayBuffer()
Promise<ArrayBuffer>
- Returns a promise that resolves with an
ArrayBuffer
representation of the request body.
- Returns a promise that resolves with an
formData()
Promise<FormData>
- Returns a promise that resolves with a
FormData
representation of the request body.
- Returns a promise that resolves with a
json()
Promise<Object>
- Returns a promise that resolves with a JSON representation of the request body.
text()
Promise<string>
- Returns a promise that resolves with a string (text) representation of the request body.
The request context
The Request
context is the context of the "fetch"
event callback. It is important to note that due to how workers are executed, asynchronous tasks (e.g. fetch
) can only be run inside the request context.
The request context is available inside of the FetchEvent
handler:
addEventListener("fetch", event => { // Request context available here event.respondWith(/*...*/)})
When passing a promise to fetch event .respondWith()
If you pass a Response promise to the fetch event .respondWith()
method, the request context is active during any asynchronous tasks which run before the Response promise has settled. You can pass the event to an async handler, for example:
addEventListener("fetch", event => { event.respondWith(eventHandler(event))})
// No request context available here
async function eventHandler(event){ // Request context available here return new Response("Hello, Workers!")}
Errors when attempting to access an inactive Request
context
Any attempt to use APIs such as fetch()
or access the Request
context during script startup will throw an exception:
const promise = fetch("https://example.com/") // Errorasync function eventHandler(event){..}
This code snippet will throw during script startup, and the "fetch"
event
listener will never be registered.