Request·续
index.jsjs
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 alive
await writer.write(enc.encode("ping\r\n"));
await scheduler.wait(1000);
}
}
```
*index.tsts*
```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 alive
await writer.write(enc.encode('ping\r\n'));
await scheduler.wait(1000);
}
}
```
- `url` string read-only
- Contains the URL of the request.
### `IncomingRequestCfProperties`
In addition to the properties on the standard [`Request` ↗︎](https://developer.mozilla.org/en-US/docs/Web/API/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:
- `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`, `signedAgent`, `staticResource`, `ja3Hash`, `ja4`, and `detectionIds`. Refer to [Bot Management Variables](https://developers.cloudflare.com/bots/reference/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"`.
- `clientQuicRtt` number | undefined
- The smoothed round-trip time (RTT) between Cloudflare and the client for QUIC connections, in milliseconds. Only present when the client connected over QUIC (HTTP/3). For example, `42`.
- `clientTcpRtt` number | undefined
- The smoothed round-trip time (RTT) between the client and Cloudflare for TCP connections, in milliseconds. Only present when the client connected over TCP (HTTP/1 and HTTP/2). For example, `22`.
- `colo` string
- The three-letter [`IATA` ↗︎](https://en.wikipedia.org/wiki/IATA_airport_code) airport code of the data center that the request hit, for example, `"DFW"`.
- `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"`.
- `edgeL4` Object | undefined
- Layer 4 transport statistics for the connection between the client and Cloudflare. Contains the following property:
- `deliveryRate` number - The most recent data delivery rate estimate for the connection, in bytes per second. For example, `123456`.
- `isEUCountry` string | null
- If the country of the incoming request is in the EU, this will return `"1"`. Otherwise, this property is either omitted or `false`.
- `httpProtocol` string
- HTTP Protocol, for example, `"HTTP/2"`.
- `hostMetadata` Object | 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](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/), and how it is exposed on the `hostMetadata` field.
- `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
- Various details about the client certificate (for mTLS connections). Refer to [Client certificate variables](https://developers.cloudflare.com/ssl/client-certificates/client-certificate-variables/) for more details.
- `tlsClientCiphersSha1` string
- 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="`.
- `tlsClientExtensionsSha1` string
- The SHA-1 hash (Base64-encoded) of the TLS client extensions sent during the handshake, encoded in big-endian format. For example, `"OWFiM2I5ZDc0YWI0YWYzZmFkMGU0ZjhlYjhiYmVkMjgxNTU5YTU2Mg=="`.
- `tlsClientExtensionsSha1Le` string
- The SHA-1 hash (Base64-encoded) of the TLS client extensions sent during the handshake, encoded in little-endian format. For example, `"7zIpdDU5pvFPPBI2/PCzqbaXnRA="`.
- `tlsClientHelloLength` string
- The length of the client hello message sent in a [TLS handshake ↗︎](https://www.cloudflare.com/learning/ssl/what-happens-in-a-tls-handshake/). For example, `"508"`. Specifically, the length of the bytestring of the client hello.
- `tlsClientRandom` string
- The value of the 32-byte random value provided by the client in a [TLS handshake ↗︎](https://www.cloudflare.com/learning/ssl/what-happens-in-a-tls-handshake/). Refer to [RFC 8446 ↗︎](https://datatracker.ietf.org/doc/html/rfc8446#section-4.1.2) for more details.
- `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
- If known, the [ISO 3166-2 ↗︎](https://en.wikipedia.org/wiki/ISO_3166-2) name for the first level region associated with the IP address of the incoming request, for example, `"Texas"`.
- `regionCode` string | null
- If known, the [ISO 3166-2 ↗︎](https://en.wikipedia.org/wiki/ISO_3166-2) code for the first-level region associated with the IP address of the incoming request, for example, `"TX"`.
- `timezone` string
- Timezone of the incoming request, for example, `"America/Chicago"`.
Caution
The `request.cf` object is not available in the Cloudflare Workers dashboard or Playground preview editor.
---
## Methods
### Instance methods
These methods are only available on an instance of a `Request` object or through its prototype.
- `clone()` : Request
- Creates a copy of the `Request` object.
- `arrayBuffer()` : Promise\<ArrayBuffer>
- Returns a promise that resolves with an [`ArrayBuffer` ↗︎](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) representation of the request body.
- `formData()` : Promise\<FormData>
- Returns a promise that resolves with a [`FormData` ↗︎](https://developer.mozilla.org/en-US/docs/Web/API/FormData) representation of the request body.
- `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
Each time a Worker is invoked by an incoming HTTP request, the [`fetch()` handler](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch) 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`](https://developers.cloudflare.com/workers/runtime-apis/fetch/)) can only be run inside the `Request` context:
```js
export default {
async fetch(request, env, ctx) {
// Request context starts here
return new Response('Hello World!');
},
};
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.
Set the Content-Length header
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.
Differences
The Workers implementation of the Request interface includes several extensions to the web standard Request API. These differences are intentional and provide additional functionality specific to the Workers runtime.
TypeScript users
Workers type definitions (from @cloudflare/workers-types or generated via wrangler types) define a Request type that includes Workers-specific properties like cf. This type is not directly compatible with the standard Request type from lib.dom.d.ts. If you are working with code that uses both Workers types and standard web types, you may need to use type assertions or create a new Request object.
The cf property
Workers adds a cf property to the Request object that contains Cloudflare-specific metadata about the incoming request. This property is not part of the web standard, and is only available in the Workers runtime. Refer to IncomingRequestCfProperties for details.
The headers property
The headers property returns a Workers-specific Headers object that includes additional methods like getAll() for Set-Cookie headers. Refer to the Headers documentation for details on how the Workers Headers implementation differs from the web standard.
Immutability
Incoming Request objects passed to the fetch() handler are immutable. To modify properties of an incoming request, you must create a new Request object.
Related resources
- 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?
YesNo
On this page
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/workers/runtime-apis/request/#page","headline":"Request","description":"Interface that represents an HTTP request.","url":"https://developers.cloudflare.com/workers/runtime-apis/request/","inLanguage":"en","image":"https://developers.cloudflare.com/workers/runtime-apis/request/og.png?v=d9715d666d09fc6d","dateModified":"2026-10-18","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
description: Interface that represents an HTTP response. title: Response image: https://developers.cloudflare.com/workers/runtime-apis/response/og.png?v=5a3e3f032dcd14c6
Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/workers/llms.txt
Use this file to discover all available pages before exploring further.
Docs