HTTP header value contains invalid characters
Production Risk
High security risk if user input reaches header values without sanitisation.
Thrown when a header value passed to an HTTP API contains characters not permitted by the HTTP specification, such as raw newline or carriage-return characters. These characters are dangerous because they can be used for HTTP response splitting attacks, so Node.js rejects them outright.
- 1Header value contains \r or \n characters
- 2User-supplied data injected into a header value without sanitisation
- 3Null bytes or other control characters in the header value
Triggered when any HTTP header-setting method receives a value with forbidden characters.
const http = require('http');
http.createServer((req, res) => {
const userInput = 'value\r\nInjected-Header: evil';
res.setHeader('X-User', userInput); // throws
res.end();
}).listen(3000);expected output
TypeError [ERR_HTTP_INVALID_HEADER_VALUE]: Invalid value "value\r\nInjected-Header: evil" for header "X-User"
Fix
Strip or encode control characters from header values
WHEN When header values come from user input or external data
const safeValue = userInput.replace(/[\r\n]/g, '');
res.setHeader('X-User', safeValue);Why this works
Removing CR/LF characters prevents HTTP response splitting and satisfies the validator.
const http = require('http');
http.createServer((req, res) => {
const userInput = 'value\r\nInjected-Header: evil';
res.setHeader('X-User', userInput); // throws
res.end();
}).listen(3000); // this triggers ERR_HTTP_INVALID_HEADER_VALUEtry {
// operation that may throw ERR_HTTP_INVALID_HEADER_VALUE
riskyOperation()
} catch (err) {
if (err.code === 'ERR_HTTP_INVALID_HEADER_VALUE') {
console.error('ERR_HTTP_INVALID_HEADER_VALUE:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_http_invalid_header_value(...args) {
// validate args here
return performOperation(...args)
}✕ Insert raw user input into HTTP headers
Newlines in header values enable HTTP response splitting, a serious security vulnerability.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev