This error occurs when Node.js receives HTTP response headers that contain invalid characters or do not comply with strict HTTP/1.1 standards. Node.js v12+ uses a stricter HTTP parser that rejects malformed headers that browsers might accept.
The HPE_INVALID_HEADER_TOKEN error is thrown by Node.js's HTTP parser when it encounters malformed or invalid characters in HTTP response headers. The "HPE" prefix stands for "HTTP Parser Error," indicating the error originates from the low-level HTTP parsing layer. Node.js version 12 introduced a stricter HTTP parser (llhttp) that enforces HTTP/1.1 specification compliance more rigorously than previous versions. While web browsers often tolerate non-compliant headers, Node.js rejects them to prevent potential security issues and ensure proper protocol adherence. This error typically occurs when making HTTP requests to servers that send response headers containing invalid characters, unexpected whitespace, control characters, or headers that violate the HTTP specification. Common culprits include servers behind certain CDNs (like Imperva/Incapsula) or legacy systems with non-compliant implementations.
Check the full error message to confirm it's a parsing issue:
# Look for error details in your logs
Error: Parse Error: Invalid header value char
at TLSSocket.socketOnData (_http_client.js:xxx:xx)
at TLSSocket.emit (events.js:xxx:xx)
Code: HPE_INVALID_HEADER_TOKENThe error occurs after the request is sent but before the response is fully processed, indicating the server's response headers are the issue.
Node.js provides a legacy parser option that is more lenient with malformed headers:
# Run your application with the legacy parser
node --http-parser=legacy index.js
# Or set it as an environment variable
export NODE_OPTIONS="--http-parser=legacy"
node index.jsImportant: This is a temporary workaround. The legacy parser may be removed in future Node.js versions and doesn't address the underlying server issue.
If you're using axios, enable the insecureHTTPParser option to use a more lenient parser:
const axios = require('axios');
// For a single request
const response = await axios.get('https://example.com', {
httpAgent: new require('http').Agent({ insecureHTTPParser: true }),
httpsAgent: new require('https').Agent({ insecureHTTPParser: true })
});
// Or set it globally
const http = require('http');
const https = require('https');
const httpAgent = new http.Agent({ insecureHTTPParser: true });
const httpsAgent = new https.Agent({ insecureHTTPParser: true });
axios.defaults.httpAgent = httpAgent;
axios.defaults.httpsAgent = httpsAgent;Warning: Only use this when absolutely necessary, as it bypasses security-related HTTP validation.
For native Node.js HTTP requests, pass the insecureHTTPParser option:
const https = require('https');
const options = {
hostname: 'example.com',
port: 443,
path: '/api/data',
method: 'GET',
insecureHTTPParser: true // Enable lenient parsing
};
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(data);
});
});
req.on('error', (error) => {
console.error(error);
});
req.end();If you cannot modify the server and need immediate relief, consider using Node.js 10 or 11 temporarily:
# Using nvm (Node Version Manager)
nvm install 10
nvm use 10
# Verify version
node --versionImportant: This is not a long-term solution as older Node.js versions reach end-of-life and miss security updates. Use this only as a temporary measure while you implement proper fixes.
If you're integrating with a third-party API, report the issue:
1. Document the specific error and Node.js version
2. Provide the request that triggers the error
3. Reference the HTTP/1.1 specification (RFC 7230)
4. Request they fix their header implementation
Example message:
Our application fails to connect from Node.js v12+ with error
HPE_INVALID_HEADER_TOKEN. This indicates your server is sending
HTTP headers with invalid characters that violate RFC 7230.
While browsers tolerate this, Node.js's strict parser rejects it.
Please review your response headers for control characters or
invalid whitespace.Why Node.js is stricter than browsers:
Node.js is often used for server-to-server communication where security and protocol compliance are critical. Browsers, designed for human interaction, implement more lenient parsers to handle the "wild west" of web servers. Node.js prioritizes correctness and security over compatibility with non-compliant servers.
The llhttp parser:
Node.js v12 switched from the older http_parser (written in C) to llhttp (also in C but with stricter validation). This new parser:
- Validates headers against RFC 7230/7231 more strictly
- Rejects control characters (0x00-0x1F, 0x7F) in header values
- Enforces proper whitespace handling
- Improves performance while increasing security
Security implications:
Malformed headers can be exploited for:
- HTTP request smuggling attacks
- Cache poisoning
- Header injection vulnerabilities
Using insecureHTTPParser or the legacy parser disables these protections. Only use these options when connecting to trusted servers where you cannot fix the root cause.
CDN and anti-scraping considerations:
Some CDNs deliberately send malformed headers to block automated clients. If you're web scraping:
1. Ensure you have permission to scrape the site
2. Consider using proper APIs instead of scraping
3. Respect robots.txt and rate limits
4. Be aware that workarounds may violate terms of service
Long-term solution:
The correct fix is always to ensure servers send compliant HTTP headers. If you control the server, audit your:
- Web server configuration (nginx, Apache, etc.)
- Application code that sets custom headers
- Middleware or proxies that modify headers
- CDN or WAF configurations
Error: Listener already called (once event already fired)
EventEmitter listener already called with once()
Error: EACCES: permission denied, open '/root/file.txt'
EACCES: permission denied
Error: Invalid encoding specified (stream encoding not supported)
How to fix Invalid encoding error in Node.js readable streams
Error: EINVAL: invalid argument, open
EINVAL: invalid argument, open
TypeError: readableLength must be a positive integer (stream config)
TypeError: readableLength must be a positive integer in Node.js streams