Request
The Request ↗ interface represents an HTTP request and is part of the Fetch API.
The most common way you will encounter a Request object is as a property of an incoming request:
export default { async fetch(request, env, ctx) { return new Response('Hello World!'); },};You may also want to construct a Request yourself when you need to modify a request object, because the incoming request parameter that you receive from the fetch() handler is immutable.
export default { async fetch(request, env, ctx) { const url = "https://example.com"; const modifiedRequest = new Request(url, request); // ... },};The fetch() handler invokes the Request constructor. The RequestInit and RequestInitCfProperties types defined below also describe the valid parameters that can be passed to the fetch() handler.
let request = new Request(input, options)-
inputstring | Request- Either a string that contains a URL, or an existing
Requestobject.
- Either a string that contains a URL, or an existing
-
optionsoptions optional- Optional options object that contains settings to apply to the
Request.
- Optional options object that contains settings to apply to the
An object containing properties that you want to apply to the request.
-
cacheundefined | 'no-store' | 'no-cache'optional- Standard HTTP
cacheheader. Onlycache: 'no-store'andcache: 'no-cache'are supported. Any other cache header will result in aTypeErrorwith the messageUnsupported cache mode: <attempted-cache-mode>.
- Standard HTTP
-
cfRequestInitCfProperties optional- Cloudflare-specific properties that can be set on the
Requestthat control how Cloudflare’s global network handles the request.
- Cloudflare-specific properties that can be set on the
-
methodstring optional- The HTTP request method. The default is
GET. In Workers, all HTTP request methods ↗ are supported, except forCONNECT↗.
- The HTTP request method. The default is
-
headersHeaders optional -
bodystring | ReadableStream | FormData | URLSearchParams optional- The request body, if any.
- Note that a request using the GET or HEAD method cannot have a body.
-
redirectstring optional- The redirect mode to use:
follow,error, ormanual. The default for a newRequestobject isfollow. Note, however, that the incomingRequestproperty of aFetchEventwill have redirect modemanual.
- The redirect mode to use:
-
signalAbortSignal optional- If provided, the request can be canceled by triggering an abort on the corresponding
AbortController.
- If provided, the request can be canceled by triggering an abort on the corresponding
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 generating types by running wrangler types to ensure proper use of the cf object.
-
appsboolean optional- Whether Cloudflare Apps ↗ should be enabled for this request. Defaults to
true.
- Whether Cloudflare Apps ↗ should be enabled for this request. Defaults to
-
cacheEverythingboolean optional- Treats all content as static and caches all file types beyond the Cloudflare default cached content. Respects cache headers from the origin web server. This is equivalent to setting the Page Rule Cache Level (to Cache Everything). Defaults to
false. This option applies toGETandHEADrequest methods only.
- Treats all content as static and caches all file types beyond the Cloudflare default cached content. Respects cache headers from the origin web server. This is equivalent to setting the Page Rule Cache Level (to Cache Everything). Defaults to
-
cacheKeystring 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.
-
cacheTagsArray<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.
-
cacheTtlnumber optional- 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). The value must be zero or a positive number. A value of
0indicates that the cache asset expires immediately. This option applies toGETandHEADrequest methods only.
- 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). The value must be zero or a positive number. A value of
-
cacheTtlByStatus{ [key: string]: number }optional- This option is a version of the
cacheTtlfeature 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 of0indicates that the cache asset expires immediately. Any negative value instructs Cloudflare not to cache at all. This option applies toGETandHEADrequest methods only.
- This option is a version of the
-
imageObject | null optional- Enables Image Resizing for this request. The possible values are described in Transform images via Workers documentation.
-
mirageboolean optional- Whether Mirage ↗ (deprecated) should be enabled for this request, if otherwise configured for this zone. Defaults to
true.
- Whether Mirage ↗ (deprecated) should be enabled for this request, if otherwise configured for this zone. Defaults to
-
polishstring optional- Sets Polish ↗ mode. The possible values are
lossy,losslessoroff.
- Sets Polish ↗ mode. The possible values are
-
resolveOverridestring optional- Directs the request to an alternate origin server by overriding the DNS lookup. The value of
resolveOverridespecifies an alternate hostname which will be used when determining the origin IP address, instead of using the hostname specified in the URL. TheHostheader of the request will still match what is in the URL. Thus,resolveOverrideallows a request to be sent to a different server than the URL /Hostheader specifies. However,resolveOverridewill only take effect if both the URL host and the host specified byresolveOverrideare 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 theHostheader pointing within your zone), first create a CNAME record within your zone pointing to the outside host, and then setresolveOverrideto point at the CNAME record. Note that, for security reasons, it is not possible to set theHostheader 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
-
scrapeShieldboolean optional- 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
-
webpboolean optional
All properties of an incoming Request object (the request you receive from the fetch() handler) are read-only. To modify the properties of an incoming request, create a new Request object and pass the options to modify to its constructor.
-
bodyReadableStream read-only- Stream of the body contents.
-
bodyUsedBoolean read-only- Declares whether the body has been used in a response yet.
-
cfIncomingRequestCfProperties read-only- An object containing properties about the incoming request provided by Cloudflare’s global network.
- This property is read-only (unless created from an existing
Request). To modify its values, pass in the new values on thecfkey of theinitoptions argument when creating a newRequestobject.
-
headersHeaders read-only-
Compared to browsers, Cloudflare Workers imposes very few restrictions on what headers you are allowed to send. For example, a browser will not allow you to set the
Cookieheader, since the browser is responsible for handling cookies itself. Workers, however, has no special understanding of cookies, and treats theCookieheader like any other header.
-
methodstring read-only- Contains the request’s method, for example,
GET,POST, etc.
- Contains the request’s method, for example,
-
redirectstring read-only- The redirect mode to use:
follow,error, ormanual. Thefetchmethod will automatically follow redirects if the redirect mode is set tofollow. If set tomanual, the3xxredirect response will be returned to the caller as-is. The default for a newRequestobject isfollow. Note, however, that the incomingRequestproperty of aFetchEventwill have redirect modemanual.
- The redirect mode to use:
-
signalAbortSignal read-only- The
AbortSignalcorresponding to this request. If you use theenable_request_signalcompatibility flag, you can attach an event listener to the signal. This allows you to perform cleanup tasks or write to logs before your Worker's invocation ends. For example, if you run the Worker below, and then abort the request from the client, a log will be written:index.js export default {async fetch(request, env, ctx) {// This sets up an event listener that will be called if the client disconnects from your// worker.request.signal.addEventListener("abort", () => {console.log("The request was aborted!");});const { readable, writable } = new IdentityTransformStream();sendPing(writable);return new Response(readable, {headers: { "Content-Type": "text/plain" },});},};async function sendPing(writable) {const writer = writable.getWriter();const enc = new TextEncoder();for (;;) {// Send 'ping' every second to keep the connection aliveawait writer.write(enc.encode("ping\r\n"));await scheduler.wait(1000);}}index.ts export default {async fetch(request, env, ctx): Promise<Response> {// This sets up an event listener that will be called if the client disconnects from your// worker.request.signal.addEventListener('abort', () => {console.log('The request was aborted!');});const { readable, writable } = new IdentityTransformStream();sendPing(writable);return new Response(readable, { headers: { 'Content-Type': 'text/plain' } });},} satisfies ExportedHandler<Env>;async function sendPing(writable: WritableStream): Promise<void> {const writer = writable.getWriter();const enc = new TextEncoder();for (;;) {// Send 'ping' every second to keep the connection aliveawait writer.write(enc.encode('ping\r\n'));await scheduler.wait(1000);}}
- The
-
urlstring read-only- Contains the URL of the request.
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 global network.
All plans have access to:
-
asnNumber- ASN of the incoming request, for example,
395747.
- ASN of the incoming request, for example,
-
asOrganizationstring- The organization which owns the ASN of the incoming request, for example,
Google Cloud.
- The organization which owns the ASN of the incoming request, for example,
-
botManagementObject | null- Only set when using Cloudflare Bot Management. Object with the following properties:
score,verifiedBot,staticResource,ja3Hash,ja4, anddetectionIds. Refer to Bot Management Variables for more details.
- Only set when using Cloudflare Bot Management. Object with the following properties:
-
clientAcceptEncodingstring | null- If Cloudflare replaces the value of the
Accept-Encodingheader, the original value is stored in theclientAcceptEncodingproperty, for example,"gzip, deflate, br".
- If Cloudflare replaces the value of the
-
colostring- The three-letter
IATA↗ airport code of the data center that the request hit, for example,"DFW".
- The three-letter
-
countrystring | 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-IPCountryheader, for example,"US".
- Country of the incoming request. The two-letter country code in the request. This is the same value as that provided in the
-
isEUCountrystring | null- If the country of the incoming request is in the EU, this will return
"1". Otherwise, this property is either omitted orfalse.
- If the country of the incoming request is in the EU, this will return
-
httpProtocolstring- HTTP Protocol, for example,
"HTTP/2".
- HTTP Protocol, for example,
-
hostMetadataObject | undefined- Only populated when the incoming request is from a zone with custom hostname metadata. Refer to the Cloudflare for Platforms documentation for more about what you can add as custom hostname metadata, and how it is exposed on the
hostMetadatafield.
- Only populated when the incoming request is from a zone with custom hostname metadata. Refer to the Cloudflare for Platforms documentation for more about what you can add as custom hostname metadata, and how it is exposed on the
-
requestPrioritystring | null- The browser-requested prioritization information in the request object, for example,
"weight=192;exclusive=0;group=3;group-weight=127".
- The browser-requested prioritization information in the request object, for example,
-
tlsCipherstring- The cipher for the connection to Cloudflare, for example,
"AEAD-AES128-GCM-SHA256".
- The cipher for the connection to Cloudflare, for example,
-
tlsClientAuthObject | 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.
- Only set when using Cloudflare Access or API Shield (mTLS). Object with the following properties:
-
tlsClientCiphersSha1string- The SHA-1 hash (Base64-encoded) of the cipher suite sent by the client during the TLS handshake, encoded in big-endian format. For example,
"GXSPDLP4G3X+prK73a4wBuOaHRc=".
- The SHA-1 hash (Base64-encoded) of the cipher suite sent by the client during the TLS handshake, encoded in big-endian format. For example,
-
tlsClientExtensionsSha1string- The SHA-1 hash (Base64-encoded) of the TLS client extensions sent during the handshake, encoded in big-endian format. For example,
"OWFiM2I5ZDc0YWI0YWYzZmFkMGU0ZjhlYjhiYmVkMjgxNTU5YTU2Mg==".
- The SHA-1 hash (Base64-encoded) of the TLS client extensions sent during the handshake, encoded in big-endian format. For example,
-
tlsClientExtensionsSha1Lestring- The SHA-1 hash (Base64-encoded) of the TLS client extensions sent during the handshake, encoded in little-endian format. For example,
"7zIpdDU5pvFPPBI2/PCzqbaXnRA=".
- The SHA-1 hash (Base64-encoded) of the TLS client extensions sent during the handshake, encoded in little-endian format. For example,
-
tlsClientHelloLengthstring- The length of the client hello message sent in a TLS handshake ↗. For example,
"508". Specifically, the length of the bytestring of the client hello.
- The length of the client hello message sent in a TLS handshake ↗. For example,
-
tlsClientRandomstring- The value of the 32-byte random value provided by the client in a TLS handshake ↗. Refer to RFC 8446 ↗ for more details.
-
tlsVersionstring- The TLS version of the connection to Cloudflare, for example,
TLSv1.3.
- The TLS version of the connection to Cloudflare, for example,
-
citystring | null- City of the incoming request, for example,
"Austin".
- City of the incoming request, for example,
-
continentstring | null- Continent of the incoming request, for example,
"NA".
- Continent of the incoming request, for example,
-
latitudestring | null- Latitude of the incoming request, for example,
"30.27130".
- Latitude of the incoming request, for example,
-
longitudestring | null- Longitude of the incoming request, for example,
"-97.74260".
- Longitude of the incoming request, for example,
-
postalCodestring | null- Postal code of the incoming request, for example,
"78701".
- Postal code of the incoming request, for example,
-
metroCodestring | null- Metro code (DMA) of the incoming request, for example,
"635".
- Metro code (DMA) of the incoming request, for example,
-
regionstring | null- If known, the ISO 3166-2 ↗ name for the first level region associated with the IP address of the incoming request, for example,
"Texas".
- If known, the ISO 3166-2 ↗ name for the first level region associated with the IP address of the incoming request, for example,
-
regionCodestring | null- If known, the ISO 3166-2 ↗ code for the first-level region associated with the IP address of the incoming request, for example,
"TX".
- If known, the ISO 3166-2 ↗ code for the first-level region associated with the IP address of the incoming request, for example,
-
timezonestring- Timezone of the incoming request, for example,
"America/Chicago".
- Timezone of the incoming request, for example,
These methods are only available on an instance of a Request object or through its prototype.
-
clone(): Request- Creates a copy of the
Requestobject.
- 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.
Each time a Worker is invoked by an incoming HTTP request, the fetch() handler is called on your Worker. The Request context starts when the fetch() handler is called, and asynchronous tasks (such as making a subrequest using the fetch() API) can only be run inside the Request context:
export default { async fetch(request, env, ctx) { // Request context starts here return new Response('Hello World!'); },};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!")}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.
The Content-Length header will be automatically set by the runtime based on whatever the data source for the Request is. Any value manually set by user code in the Headers will be ignored. To have a Content-Length header with a specific value specified, the body of the Request must be either a FixedLengthStream or a fixed-length value just as a string or TypedArray.
A FixedLengthStream is an identity TransformStream that permits only a fixed number of bytes to be written to it.
const { writable, readable } = new FixedLengthStream(11);
const enc = new TextEncoder(); const writer = writable.getWriter(); writer.write(enc.encode("hello world")); writer.end();
const req = new Request('https://example.org', { method: 'POST', body: readable });Using any other type of ReadableStream as the body of a request will result in Chunked-Encoding being used.
- Examples: Modify request property
- Examples: Accessing the
cfobject - Reference:
Response - Write your Worker code in ES modules syntax for an optimized experience.
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Directory
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- © 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark