nodejs/node · error · TypeError
expected headers to be an array
Error message
expected headers to be an array
What it means
encodeRawHeaders expects a flat array of string field-name/value entries (the raw header list format) and throws TypeError if its argument is not an array. This guards the low-level path that converts raw header arrays into Buffers for the wire.
Source
Thrown at deps/undici/src/lib/core/util.js:545
if (Array.isArray(value)) {
for (const entry of value) {
rawHeaders.push(Buffer.from(name, 'latin1'), Buffer.from(`${entry}`, 'latin1'))
}
} else {
rawHeaders.push(Buffer.from(name, 'latin1'), Buffer.from(`${value}`, 'latin1'))
}
}
return rawHeaders
}
/**
* @param {string[]} headers
* @param {Buffer[]} headers
*/
function encodeRawHeaders (headers) {
if (!Array.isArray(headers)) {
throw new TypeError('expected headers to be an array')
}
return headers.map(x => Buffer.from(x))
}
/**
* @param {*} buffer
* @returns {buffer is Buffer}
*/
function isBuffer (buffer) {
// See, https://github.com/mcollina/undici/pull/319
return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
}
/**
* Asserts that the handler object is a request handler.
*
* @param {object} handler
* @param {string} methodView on GitHub (pinned to 1b2de5e052)
Solutions
- Supply headers as a flat array of strings: ['Name', 'Value', 'Name2', 'Value2'].
- Convert an object with Object.entries then flatten: Object.entries(h).flat().
- Confirm you are on a compatible undici version for the API you are calling.
Example fix
// before
encodeRawHeaders({ 'content-type': 'application/json' })
// after
encodeRawHeaders(['content-type', 'application/json']) Defensive patterns
Strategy: type-guard
Validate before calling
function toRawHeaders(h) {
if (Array.isArray(h)) return h
if (h && typeof h === 'object') return Object.entries(h).flat()
throw new TypeError('headers must be an array or a flat key/value object')
} Type guard
function isRawHeadersArray(h) { return Array.isArray(h) } Prevention
- Standardize on the flat-array raw header shape when calling low-level APIs.
- Convert header objects via Object.entries(...).flat().
- Confirm API/version compatibility before passing headers.
When it happens
Trigger: Calling an internal/raw API (or a diagnostic hook) that ends up in encodeRawHeaders with a non-array: an object, a string, a Map, or undefined.
Common situations: Passing a {Name: 'Value'} object where an array of pairs was expected; passing undefined because a headers field was not populated; mismatched undici version where the expected shape changed.
Related errors
- key must be ascii string
- ${optionName} must be an array
- ${optionName} must contain header names
- expected opts.skipHeaderNames to be an array, got ${typeof s
- expected opts.excludeHeaderNames to be an array, got ${typeo
AI-assisted analysis of nodejs/node@1b2de5e052 (2026-08-13).
Data as JSON: /api/errors/2b8e9de4f902b4de.
Report an issue: GitHub.