HTTP header name contains invalid characters
Production Risk
Can crash request handlers if header names come from untrusted input; also a security concern.
Thrown when a header name passed to an HTTP response or request method contains characters that are not permitted by the HTTP specification. Valid header names consist only of ASCII printable characters excluding delimiters such as parentheses, commas, slashes, colons, semicolons, angle brackets, equals, question marks, braces, and spaces.
- 1Header name contains spaces, colons, or other delimiter characters
- 2Header name is an empty string
- 3User-supplied input used directly as a header name without validation
Triggered when res.setHeader(), res.writeHead(), or req.setHeader() receives an invalid header name.
const http = require('http');
http.createServer((req, res) => {
res.setHeader('invalid header', 'value'); // space is invalid
res.end('ok');
}).listen(3000);expected output
TypeError [ERR_HTTP_INVALID_HEADER_NAME]: Invalid header name: "invalid header"
Fix 1
Use valid ASCII header names without special characters
WHEN Always — sanitise header names before setting them
res.setHeader('X-Custom-Header', 'value'); // valid
res.setHeader('Content-Type', 'text/plain'); // validWhy this works
Valid header names follow RFC 7230 token rules; removing illegal characters satisfies the validation.
Fix 2
Validate user-supplied header names
WHEN When header names come from external input
const VALID_HEADER = /^[a-zA-Z0-9-_]+$/;
if (VALID_HEADER.test(headerName)) {
res.setHeader(headerName, value);
}Why this works
Whitelisting valid characters prevents invalid names from reaching the HTTP layer.
const http = require('http');
http.createServer((req, res) => {
res.setHeader('invalid header', 'value'); // space is invalid
res.end('ok');
}).listen(3000); // this triggers ERR_HTTP_INVALID_HEADER_NAMEtry {
// operation that may throw ERR_HTTP_INVALID_HEADER_NAME
riskyOperation()
} catch (err) {
if (err.code === 'ERR_HTTP_INVALID_HEADER_NAME') {
console.error('ERR_HTTP_INVALID_HEADER_NAME:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_http_invalid_header_name(...args) {
// validate args here
return performOperation(...args)
}✕ Pass unsanitised user input as header names
Invalid characters cause an immediate throw and can be a header-injection vector.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev