Encoded data is invalid for the specified encoding
Production Risk
Can crash HTTP handlers if body decoding fails; use fatal: false for tolerant decoding.
Thrown when data passed to TextDecoder.decode() is not valid for the specified encoding. For example, passing data with invalid UTF-8 byte sequences when the encoding is set to "utf-8" with fatal mode enabled causes this error.
- 1Decoding binary data that contains invalid UTF-8 sequences with fatal mode on
- 2Receiving corrupted data from a network source and decoding without error handling
- 3Truncated multi-byte UTF-8 character sequences
Triggered when TextDecoder.decode() encounters invalid bytes and fatal is true.
const decoder = new TextDecoder('utf-8', { fatal: true });
const invalidUtf8 = Buffer.from([0xff, 0xfe]); // invalid UTF-8
decoder.decode(invalidUtf8); // throws ERR_ENCODING_INVALID_ENCODED_DATAexpected output
TypeError [ERR_ENCODING_INVALID_ENCODED_DATA]: The encoded data was not valid for encoding utf-8
Fix 1
Use fatal: false to replace invalid sequences with the replacement character
WHEN When the input may contain invalid bytes and you want best-effort decoding
const decoder = new TextDecoder('utf-8', { fatal: false });
const text = decoder.decode(Buffer.from([0xff, 0xfe]));
// Invalid bytes replaced with U+FFFD (replacement character)Why this works
fatal: false tells the decoder to substitute invalid sequences with the Unicode replacement character instead of throwing.
Fix 2
Validate and sanitise input before decoding with fatal mode
WHEN When strict validation is required
try {
const text = new TextDecoder('utf-8', { fatal: true }).decode(data);
return text;
} catch (err) {
if (err.code === 'ERR_ENCODING_INVALID_ENCODED_DATA') {
throw new Error('Received invalid UTF-8 data');
}
throw err;
}Why this works
Catching the error allows explicit handling of corrupted encoding.
const decoder = new TextDecoder('utf-8', { fatal: true });
const invalidUtf8 = Buffer.from([0xff, 0xfe]); // invalid UTF-8
decoder.decode(invalidUtf8); // throws ERR_ENCODING_INVALID_ENCODED_DATA // this triggers ERR_ENCODING_INVALID_ENCODED_DATAtry {
// operation that may throw ERR_ENCODING_INVALID_ENCODED_DATA
riskyOperation()
} catch (err) {
if (err.code === 'ERR_ENCODING_INVALID_ENCODED_DATA') {
console.error('ERR_ENCODING_INVALID_ENCODED_DATA:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_encoding_invalid_encoded_data(...args) {
// validate args here
return performOperation(...args)
}✕ Use fatal mode without handling the error for data from external sources
External data may contain invalid sequences; unhandled fatal errors crash the handler.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev