Headers.prototype.set
Sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist
Syntax
headers.set(name, value)Parameters
| Parameter | Type | Description |
|---|---|---|
| name | string | The name of the HTTP header |
| value | string | The value to set |
Return Value
undefined
Examples
const headers = new Headers()
headers.set('Content-Type', 'application/json')
headers.set('Accept', 'application/json')function addAuth(headers: Headers, token: string) {
headers.set('Authorization', `Bearer ${token}`)
return headers
}const headers = new Headers({ 'X-Version': '1' })
headers.set('X-Version', '2')
console.log(headers.get('X-Version')) // '2'Understanding Headers.prototype.set
The Headers.prototype.set method in JavaScript sets a new value for an existing header inside a Headers object, or adds the header if it does not already exist. It belongs to the Headers object and is one of the most widely used methods for working with headers values in modern JavaScript and TypeScript applications.
The method signature is headers.set(name, value). It accepts 2 parameters: name, value. When called, it returns undefined. Understanding when and how to use set() helps you write more expressive, readable code.
Common use cases for Headers.prototype.set include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like fetch-headers-get, fetch-headers-append, fetch-headers-delete, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Headers.prototype.set is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Headers.prototype.getReturns the value of the specified header from a Headers object, or null if it does not exist
Headers.prototype.appendAppends a new value onto an existing header inside a Headers object, or adds the header if it does not already exist
Headers.prototype.deleteDeletes a header from a Headers object
More Headers Methods
Other methods in the Headers object
Related Tools
More Headers Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.