ERR_HTTP_SOCKET_ENCODING
Node.jsERRORNotableHTTPHIGH confidence

Cannot change encoding on HTTP socket

Production Risk

Causes HTTP parsing to break for all subsequent requests on that connection.

What this means

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.

Why it happens
  1. 1Calling req.socket.setEncoding("utf8") inside an HTTP request handler
  2. 2Middleware that sets socket encoding for logging or debugging purposes
How to reproduce

Triggered when setEncoding() is called on a socket that is managed by the HTTP stack.

trigger — this will error
trigger — this will error
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

Read from req (not the socket) and use req.setEncoding()
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.

Code examples
Triggerjs
const http = require('http');
http.createServer((req, res) => {
  req.socket.setEncoding('utf8'); // throws
  res.end('ok');
}).listen(3000);  // this triggers ERR_HTTP_SOCKET_ENCODING
Handle in try/catchjs
try {
  // 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
  }
}
Defensive pattern to avoid itjs
// Validate inputs before calling the operation
function safe_err_http_socket_encoding(...args) {
  // validate args here
  return performOperation(...args)
}
What not to do

Call setEncoding() on req.socket or res.socket in HTTP handlers

The HTTP parser needs raw bytes; encoding the socket breaks parsing.

Same error in other languages
Sources
Official documentation ↗

Node.js Error Codes Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Node.js errors