Skip to content

Instantly share code, notes, and snippets.

@kevinxh
Last active June 26, 2024 19:16
Show Gist options
  • Save kevinxh/bc95c9353d902b00720a77d078e07b5c to your computer and use it in GitHub Desktop.
Save kevinxh/bc95c9353d902b00720a77d078e07b5c to your computer and use it in GitHub Desktop.
Node.js invalid http header demo

Nodejs invalid http header error

When attempting to set http headers with invalid characters, Nodejs will throw a TypeError.

const http = require("http");

const server = http.createServer((req, res) => {
    // Attempting to set a header with invalid characters
    res.setHeader("CF-Region", "中文");
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("Hello, world!");
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});
node:_http_outgoing:628
    throw new ERR_INVALID_CHAR('header content', name);
    ^

TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["CF-Region"]
    at ServerResponse.setHeader (node:_http_outgoing:651:3)
    at Server.<anonymous> (/Users/kevin.he/dev/nodehttpheader/index.js:5:7)
    at Server.emit (node:events:517:28)
    at parserOnIncoming (node:_http_server:1107:12)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17) {
  code: 'ERR_INVALID_CHAR'
}

Potential Solutions / Workarounds

  1. Use res.writeHead instead of res.setHeader.

res.writeHead bypasses the ascii character validation, however, this is not a direct replace because res.writeHead can only be called once before response is sent.

  1. encode the value via encodeURIComponent
const http = require("http");
const server = http.createServer((req, res) => {
// Attempting to set a header with invalid characters
res.setHeader("CF-Region", encodeURIComponent("中文"));
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, world!");
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment