Cloudflare Docs
Workers
Visit Workers on GitHub
Set theme to dark (⇧+D)

Request

The Request interface represents an HTTP request and is part of the Fetch API.

​​ Background

The most common way you will 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. 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.
  • init RequestInit optional

    • Optional options object that contains settings to apply to the Request.

​​ RequestInit

  • cf RequestInitCfProperties optional

    • Cloudflare-specific properties that can be set on the Request that control how Cloudflare’s edge handles the request.
  • method string optional

    • The HTTP request method. The default is GET.
  • headers Headers optional

  • body string | ReadableStream | FormData | URLSearchParams optional

    • The request body, if any.
  • redirect string optional

    • The redirect mode to use: follow, error, or manual. The default for a new Request object is follow. Note, however, that the incoming Request property of a FetchEvent will have redirect mode manual.

​​ 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 optional

  • cacheEverything boolean optional

  • cacheKey string optional

    • 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 Cloudflare can serve the same cached response for both.
  • cacheTags Array<string> optional

    • This option appends additional Cache-Tag headers to the response from the origin server. This allows for purges of cached content based on tags provided by the Worker, without modifications to the origin server. This is performed using the Purge by Tag feature, which is currently only available to Enterprise zones. If this option is used in a non-Enterprise zone, the additional headers will not be appended.
  • cacheTtl number optional

  • cacheTtlByStatus { [key: string]: number } optional

    • 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 }. The value can be any integer, including zero and negative integers. A value of 0 indicates that the cache asset expires immediately. Any negative value instructs Cloudflare not to cache at all. This option applies to GET and HEAD request methods only.
  • image Object | null optional

  • minify { javascript?: boolean; css?: boolean; html?: boolean; } optional

  • mirage boolean optional

  • polish string optional

  • resolveOverride string optional

    • 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. The Host 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 by resolveOverride 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 the Host header pointing within your zone), first create a CNAME record within your zone pointing to the outside host, and then set resolveOverride to point at the CNAME record. Note that, for security reasons, it is not possible to set the Host header to specify a host outside of your zone unless the request is actually being sent to that host.
  • scrapeShield boolean optional

  • webp boolean optional


​​ Properties

All properties of an incoming Request object (that is, event.request) are read only. To modify a request, create a new Request object and pass the options to modify to its constructor.

  • body ReadableStream read-only

    • Stream of the body contents.
  • bodyUsed Boolean read-only

    • Declares whether the body has been used in a response yet.
  • cf IncomingRequestCfProperties read-only

    • An object containing properties about the incoming request provided by Cloudflare’s edge network.
  • headers Headers read-only

  • method string read-only

    • Contains the request’s method, for example, GET, POST, etc.
  • redirect string read-only

    • The redirect mode to use: follow, error, or manual. The fetch method will automatically follow redirects if the redirect mode is set to follow. If set to manual, the 3xx redirect response will be returned to the caller as-is. The default for a new Request object is follow. Note, however, that the incoming Request property of a FetchEvent will have redirect mode manual.
  • url string read-only

    • 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 Number

    • ASN of the incoming request, for example, 395747.
  • asOrganization string

    • The organization which owns the ASN of the incoming request, for example, Google Cloud.
  • botManagement Object | null

    • Only set when using Cloudflare Bot Management. Object with the following properties: score, verifiedBot, staticResource, and ja3Hash. Refer to Bot Management Variables for more details.
  • clientAcceptEncoding string | null

    • If Cloudflare replaces the value of the Accept-Encoding header, the original value is stored in the clientAcceptEncoding property, for example, "gzip, deflate, br".
  • colo string

  • 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, for example, "US".
  • isEUCountry string | null

    • If the country of the incoming request is in the EU, this will return "1". Otherwise, this property will be omitted.
  • httpProtocol string

    • HTTP Protocol, for example, "HTTP/2".
  • requestPriority string | null

    • The browser-requested prioritization information in the request object, for example, "weight=192;exclusive=0;group=3;group-weight=127".
  • tlsCipher string

    • The cipher for the connection to Cloudflare, for example, "AEAD-AES128-GCM-SHA256".
  • tlsClientAuth Object | null

    • Only set when using Cloudflare Access or API Shield (mTLS). Object with the following properties: certFingerprintSHA1, certFingerprintSHA256, certIssuerDN, certIssuerDNLegacy, certIssuerDNRFC2253, certIssuerSKI, certIssuerSerial, certNotAfter, certNotBefore, certPresented, certRevoked, certSKI, certSerial, certSubjectDN, certSubjectDNLegacy, certSubjectDNRFC2253, certVerified.
  • tlsVersion string

    • The TLS version of the connection to Cloudflare, for example, TLSv1.3.
  • city string | null

    • City of the incoming request, for example, "Austin".
  • continent string | null

    • Continent of the incoming request, for example, "NA".
  • latitude string | null

    • Latitude of the incoming request, for example, "30.27130".
  • longitude string | null

    • Longitude of the incoming request, for example, "-97.74260".
  • postalCode string | null

    • Postal code of the incoming request, for example, "78701".
  • metroCode string | null

    • Metro code (DMA) of the incoming request, for example, "635".
  • region string | null

  • regionCode string | null

  • timezone string

    • Timezone of the incoming request, for example, "America/Chicago".

​​ 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.
  • arrayBuffer() Promise<ArrayBuffer>

  • formData() Promise<FormData>

  • 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 (for example, 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/") // Error
async function eventHandler(event){..}

This code snippet will throw during script startup, and the "fetch" event listener will never be registered.