INTEGRITY Cloudflare Docs

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 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.


Constructor

let request = new Request(input, options)

Parameters

options

An object containing properties that you want to apply to the request.

The cf property (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 generating types by running wrangler types to ensure proper use of the cf object.

The cf.vary property

The cf.vary object controls how Cloudflare handles request headers named by the origin Vary response header for a single fetch() request. It uses the same default and headers shape as Cache Rules Vary, and the same actions and normalization behavior as Vary.

If you omit cf.vary, Cloudflare uses other Vary behavior for the zone, including Cache Rules Vary if configured.

The origin response must include a Vary header for this setting to affect the cache key. A response containing Vary: * always bypasses cache.

The cf.vary object supports these keys:

Key Required Description
default Yes Configuration for any header name in the origin Vary response that is not included in headers.
headers No A map of lowercase request header names to configuration objects.

If the vary object is present, default is required. An empty vary object is invalid. Invalid cf.vary configurations are ignored for that request.

Each header configuration object, and the default object, must include an action key set to one of normalize, passthrough, or bypass. For guidance, refer to Actions.

Additional parameters can be specified for certain header names:

Header Additional key Description
accept media_types MIME types to keep when normalizing the Accept header. Maximum 10 items and 255 characters per item.
accept-language languages Languages to keep when normalizing the Accept-Language header. Maximum 20 items and 64 characters per item.

The default object and headers entries other than accept and accept-language support only action.

For most deployments, set default.action to bypass, add headers entries for expected origin Vary headers, and use normalize for accept and accept-language unless your origin requires raw header values.

The following limits and validation rules apply:

The following request init fragment normalizes Accept and Accept-Language, and bypasses cache for any other header in the origin Vary response:

Request init fragment
{
	"cf": {
		"vary": {
			"default": {
				"action": "bypass"
			},
			"headers": {
				"accept": {
					"action": "normalize",
					"media_types": ["text/html", "application/json"]
				},
				"accept-language": {
					"action": "normalize",
					"languages": ["en", "fr", "de"]
				}
			}
		}
	}
}

Properties

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.

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 global network.

All plans have access to:


Methods

Instance methods

These methods are only available on an instance of a Request object or through its prototype.


The Request context

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!');
	},
};

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.

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.