The Headers class represents a collection of HTTP request or response header fields.
It is fully compatible with the Fetch API standard but includes additional convenience methods for scripting environments, such as JSON conversion for debugging and serialization.
A Headers object can be used in the following contexts:
- When creating a request via
RequestInit.headers
- When reading headers from a
Response object
- When programmatically modifying header data in a script
Definition
1class Headers {
2 constructor(init?: HeadersInit)
3 append(name: string, value: string): void
4 get(name: string): string | null
5 has(name: string): boolean
6 set(name: string, value: string): void
7 delete(name: string): void
8 forEach(callback: (value: string, name: string) => void): void
9 keys(): string[]
10 values(): string[]
11 entries(): [string, string][]
12 toJson(): Record<string, string>
13}
Headers can be initialized using multiple formats:
1type HeadersInit = [string, string][] | Record<string, string> | Headers
You can create a Headers object using any of these forms:
1new Headers([["Content-Type", "application/json"]])
2new Headers({ "Authorization": "Bearer token" })
3new Headers(existingHeaders)
Constructor
Creates a new Headers instance.
You can optionally pass initial header data.
Parameters
| Parameter |
Type |
Description |
| init |
HeadersInit |
Initial header data. Can be an object, array, or another Headers instance. |
Methods
append(name: string, value: string): void
Adds a new value to an existing header field.
If the field already exists, the new value is appended instead of replacing the old one.
Example
1const headers = new Headers()
2headers.append("Accept", "application/json")
3headers.append("Accept", "text/plain") // Now "Accept" has two values
set(name: string, value: string): void
Sets a header field to a specific value.
If the field already exists, it will be overwritten.
Example
1const headers = new Headers()
2headers.set("Content-Type", "application/json")
3headers.set("Authorization", "Bearer token-123")
get(name: string): string | null
Retrieves the value of a specific header field.
Returns null if the field does not exist.
Example
1const headers = new Headers({ "Content-Type": "application/json" })
2console.log(headers.get("Content-Type")) // "application/json"
has(name: string): boolean
Checks whether a specific header field exists.
Example
1const headers = new Headers({ "Accept": "application/json" })
2console.log(headers.has("Accept")) // true
3console.log(headers.has("Authorization")) // false
delete(name: string): void
Removes a specific header field.
Example
1const headers = new Headers({
2 "Accept": "application/json",
3 "Cache-Control": "no-cache"
4})
5headers.delete("Cache-Control")
forEach(callback: (value: string, name: string) => void): void
Iterates over all header fields and executes the callback for each pair.
Example
1const headers = new Headers({
2 "Accept": "application/json",
3 "User-Agent": "ScriptingApp/1.0"
4})
5
6headers.forEach((value, name) => {
7 console.log(`${name}: ${value}`)
8})
keys(): string[]
Returns an array containing all header names.
1const headers = new Headers({
2 "Accept": "application/json",
3 "User-Agent": "Scripting"
4})
5console.log(headers.keys()) // ["accept", "user-agent"]
Note: Header names are case-insensitive and normalized to lowercase.
values(): string[]
Returns an array containing all header values.
1const headers = new Headers({
2 "Accept": "application/json",
3 "User-Agent": "Scripting"
4})
5console.log(headers.values()) // ["application/json", "Scripting"]
entries(): [string, string][]
Returns an array of [name, value] pairs representing all headers.
Example
1const headers = new Headers({
2 "Accept": "application/json",
3 "Cache-Control": "no-cache"
4})
5console.log(headers.entries())
6// [["accept", "application/json"], ["cache-control", "no-cache"]]
toJson(): Record<string, string>
Converts the header collection into a plain JSON object for easy serialization and debugging.
Example
1const headers = new Headers({
2 "Content-Type": "application/json",
3 "Authorization": "Bearer token"
4})
5
6console.log(headers.toJson())
7// { "content-type": "application/json", "authorization": "Bearer token" }
Usage Examples
1const headers = new Headers()
2headers.set("Content-Type", "application/json")
3headers.set("Authorization", "Bearer token-xyz")
4
5const response = await fetch("https://api.example.com/user", {
6 method: "POST",
7 headers,
8 body: JSON.stringify({ name: "Tom" }),
9})
1const response = await fetch("https://example.com/data")
2console.log("Content-Type:", response.headers.get("Content-Type"))
3console.log("Server:", response.headers.get("Server"))
Example 3 — Converting to JSON for Logging
1const response = await fetch("https://example.com/api")
2console.log("Response Headers:", response.headers.toJson())
1const response = await fetch("https://example.com/info")
2if (response.headers.has("Set-Cookie")) {
3 console.log("The response contains a Set-Cookie header")
4}
Relationships with Other Classes
| Class |
Description |
Request |
Headers can be defined in RequestInit.headers when creating requests. |
Response |
Access response headers via response.headers. |
fetch() |
Both requests and responses use Headers to manage header data. |
Cookie |
Cookies returned in headers can be parsed into structured objects in response.cookies. |
Notes
- Case-insensitivity: Header names are case-insensitive and stored in lowercase form.
- Multi-value headers: Use
append() to add multiple values for the same header (e.g., for Accept or Cookie).
- System headers: Certain system-managed headers (e.g.,
Host, Connection) may be ignored or overwritten by the iOS networking stack.
- Serialization: The
toJson() method is useful for logging, debugging, or serializing header data.
Summary
The Headers class is a foundational component of the Scripting networking system, providing a consistent and convenient interface for managing HTTP headers.
It enables developers to:
- Add, modify, and remove headers dynamically
- Read and iterate through response headers
- Work with both request and response headers in a unified way
- Output structured header data for logging and debugging