Headers
Background
All HTTP request and response headers are available through the Headers API.
When a header name possesses multiple values, those values will be concatenated as a single, comma-delimited string value. This means that Headers.get will always return a string or a null value. This applies to all header names except for Set-Cookie, which requires Headers.getAll. This is documented below in Differences
.
let headers = new Headers();
headers.get('x-foo'); //=> null
headers.set('x-foo', '123');headers.get('x-foo'); //=> "123"
headers.set('x-foo', 'hello');headers.get('x-foo'); //=> "hello"
headers.append('x-foo', 'world');headers.get('x-foo'); //=> "hello, world"
Differences
Despite the fact that the
Headers.getAllmethod has been made obsolete, Cloudflare still offers this method but only for use with theSet-Cookieheader. This is because cookies will often contain date strings, which include commas. This can make parsing multiple values in aSet-Cookieheader more difficult. Any attempts to useHeaders.getAllwith other header names will throw an error. A brief historyHeaders.getAllis available in this GitHub issue.In Cloudflare Workers, the
Headers.getmethod returns aUSVStringinstead of aByteString, which is specified by the spec. For most scenarios, this should have no noticeable effect. To compare the differences between these two string classes, please refer to this Playground example.
Cloudflare headers
Cloudflare sets a number of its own custom headers on incoming requests and outgoing responses. While some may be used for its own tracking and bookkeeping, many of these can be useful to your own applications – or Workers – too.
Request headers
CF-Connecting-IP: In same-zone Worker subrequests, the value ofCF-Connecting-IPreflects the value ofx-real-ip(the client’s IP).x-real-ipcan be altered by the user in their Worker script.In cross-zone subrequests from one Cloudflare customer zone to another Cloudflare customer zone, the
CF-Connecting-IPvalue will be set to the Worker client IP address'2a06:98c0:3600::103'for security reasons.For Worker subrequests destined for a non-Cloudflare customer zone, the
CF-Connecting-IPandx-real-ipheaders will both reflect the client’s IP address, with only thex-real-ipheader able to be altered.When no Worker subrequest is triggered,
cf-connecting-ipreflects the client’s IP address and thex-real-ipheader is stripped.CF-Worker: Added to all Worker subrequests sent viafetch(). Set to the name of the zone which owns the Worker making the subrequest. For example, a Worker script on route forfoo.example.com/*fromexample.comwill have all subrequests with the header:CF-Worker:example.comThe intended purpose of this header is to provide a means for recipients (e.g., origins, load balancers, other Workers) to recognize, filter, and route traffic generated by Workers on specific zones.
CF-EW-Via: Used for loop detection, similar to theCDN-Loopheader.