How to fix Error: HPE_INVALID_HEADER_TOKEN: invalid header token in Node.js
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.
Quick fix
Fixes HPE_INVALID_HEADER_TOKEN
# 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_TOKEN- Verify the error is related to response headers
- Use the legacy HTTP parser (quick workaround)
- Use insecureHTTPParser option with axios
- Configure native http/https modules with insecure parser
# Look for error details in your logsError: Parse Error: Invalid header value charat TLSSocket.socketOnData (_http_client.js:xxx:xx)at TLSSocket.emit (events.js:xxx:xx)Code: HPE_INVALID_HEADER_TOKENError: HPE_INVALID_HEADER_TOKEN: invalid header token
What this error means
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.
Typical symptoms
- HTTP requests fail with "Parse Error: Invalid header value char"
- Error message includes "HPE_INVALID_HEADER_TOKEN" code
- Requests work in browsers but fail in Node.js applications
- Issue appeared after upgrading from Node.js 10 or 11 to version 12+
- Error occurs when using axios, node-fetch, or native http/https modules
- Intermittent failures when connecting to specific third-party APIs
- Web scraping scripts that previously worked now throw parsing errors
Common causes
- Server sends HTTP headers with control characters (non-printable ASCII characters)
- Response headers contain unexpected whitespace before or after values
- Server behind CDN (Imperva, Incapsula) adds non-compliant headers for anti-scraping
- Legacy server implementations that predate strict HTTP/1.1 specifications
- Headers with invalid characters in field names or values
- Server sends malformed header continuation lines
- Proxy or load balancer modifies headers incorrectly
- Node.js upgraded from version 11 or earlier to version 12+ with stricter parser
How to fix "Error: HPE_INVALID_HEADER_TOKEN: invalid header token"
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.Advanced notes
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
Frequently asked questions
- What does "HPE_INVALID_HEADER_TOKEN" mean?
- 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. 1 specification compliance more rigorously than previous versions.
- How do I fix "HPE_INVALID_HEADER_TOKEN"?
- 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.
- What causes "HPE_INVALID_HEADER_TOKEN"?
- Server sends HTTP headers with control characters (non-printable ASCII characters) Response headers contain unexpected whitespace before or after values Server behind CDN (Imperva, Incapsula) adds non-compliant headers for anti-scraping
- Is the "HPE_INVALID_HEADER_TOKEN" error serious?
- It is a medium-severity error โ more of a blocker than a risk. The steps above resolve it.
Official resources & further reading
- ๐Node.js Official Documentation
- ๐Node.js HTTP headers validation and parsing(Official Docs)
- ๐
- ๐
- ๐