Cannot change encoding on HTTP socket
Production Risk
Causes HTTP parsing to break for all subsequent requests on that connection.
Thrown when socket.setEncoding() is called on the underlying socket of an HTTP connection. Node.jss HTTP parser requires raw binary data from the socket; setting a string encoding on the socket corrupts the parsers input and is therefore forbidden.
- 1Calling req.socket.setEncoding("utf8") inside an HTTP request handler
- 2Middleware that sets socket encoding for logging or debugging purposes
Triggered when setEncoding() is called on a socket that is managed by the HTTP stack.
const http = require('http');
http.createServer((req, res) => {
req.socket.setEncoding('utf8'); // throws
res.end('ok');
}).listen(3000);expected output
Error [ERR_HTTP_SOCKET_ENCODING]: Changing the socket encoding is not allowed per RFC7230 Section 3
Fix
Read from req (not the socket) and use req.setEncoding()
WHEN When you need to read request body as a string
http.createServer((req, res) => {
req.setEncoding('utf8'); // set encoding on the stream, not the socket
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => res.end(body));
}).listen(3000);Why this works
The IncomingMessage stream has its own encoding layer; setEncoding() on it does not affect the raw socket.
const http = require('http');
http.createServer((req, res) => {
req.socket.setEncoding('utf8'); // throws
res.end('ok');
}).listen(3000); // this triggers ERR_HTTP_SOCKET_ENCODINGtry {
// operation that may throw ERR_HTTP_SOCKET_ENCODING
riskyOperation()
} catch (err) {
if (err.code === 'ERR_HTTP_SOCKET_ENCODING') {
console.error('ERR_HTTP_SOCKET_ENCODING:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_http_socket_encoding(...args) {
// validate args here
return performOperation(...args)
}✕ Call setEncoding() on req.socket or res.socket in HTTP handlers
The HTTP parser needs raw bytes; encoding the socket breaks parsing.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev