How to fix TypeError: Argument must be a valid hex string in Node.js
This error occurs when attempting to create a Buffer with a malformed hexadecimal string. The hex string must contain an even number of valid hexadecimal characters, with each pair representing a single byte.
Quick fix
Fixes ERR_INVALID_HEX_STRING
const hexString = "1a2b"; // Valid - 4 characters (2 bytes)
const invalid = "1a2"; // Invalid - 3 characters (odd)
if (hexString.length % 2 !== 0) {
console.error("Hex string has odd length:", hexString.length);
}- Verify the hex string length
- Validate hex characters
- Trim and normalize input
- Implement validation helper
const hexString = "1a2b"; // Valid - 4 characters (2 bytes)const invalid = "1a2"; // Invalid - 3 characters (odd)if (hexString.length % 2 !== 0) {console.error("Hex string has odd length:", hexString.length);}TypeError: Argument must be a valid hex string
What this error means
Node.js throws this TypeError when you try to convert a hexadecimal string to a Buffer using Buffer.from() or the deprecated new Buffer() constructor with invalid hex data. The error specifically indicates that the provided string either has an odd number of characters (each hex byte requires exactly 2 characters) or contains non-hexadecimal characters. Hexadecimal strings must consist exclusively of valid hex digits (0-9, a-f, A-F) with an even count for proper byte pairing.
Typical symptoms
- Buffer.from() or Buffer() constructor throws 'Invalid hex string' error
- Application crashes when processing hex-encoded data from external sources
- Data parsing fails when reading hex strings from APIs, files, or user input
- Crypto operations fail when converting hex-encoded keys or hashes to buffers
- Error occurs sporadically when processing variable-length hex strings
Common causes
- Hex string has an odd number of characters (e.g., '1a2' instead of '1a2b')
- String contains non-hexadecimal characters (e.g., spaces, letters outside a-f, special characters)
- Trimming operations added/removed characters changing string length parity
- Data passed from external source contains unexpected formatting or encoding
- Case sensitivity issue or incorrect character escaping in the hex string
How to fix "TypeError: Argument must be a valid hex string"
Check that your hex string has an even number of characters. Each hexadecimal digit pair represents one byte.
const hexString = "1a2b"; // Valid - 4 characters (2 bytes)
const invalid = "1a2"; // Invalid - 3 characters (odd)
if (hexString.length % 2 !== 0) {
console.error("Hex string has odd length:", hexString.length);
}If your string has odd length, you may need to pad it:
const hexString = "1a2";
const padded = hexString.padStart(hexString.length + 1, "0"); // "01a2"
const buffer = Buffer.from(padded, "hex");Ensure the string contains only valid hexadecimal characters (0-9, a-f, A-F). Invalid characters will cause the error or produce unexpected results.
const hexRegex = /^[0-9a-fA-F]*$/;
const hexString = "1a2bZZ"; // Contains invalid characters Z, Z
if (!hexRegex.test(hexString)) {
console.error("Hex string contains invalid characters");
}
const validHex = "1a2b3c"; // Valid
const buffer = Buffer.from(validHex, "hex");Remove whitespace and normalize the hex string before conversion:
const rawInput = " 1a 2b 3c "; // From external source
const normalized = rawInput.trim().replace(/\s+/g, "").toLowerCase();
if (normalized.length % 2 !== 0) {
throw new Error("Invalid hex string length");
}
const buffer = Buffer.from(normalized, "hex");
console.log(buffer); // <Buffer 1a 2b 3c>Create a helper function to safely convert hex strings to buffers:
function safeHexToBuffer(hexString) {
const cleaned = hexString.trim().replace(/\s+/g, "").toLowerCase();
// Validate length
if (cleaned.length % 2 !== 0) {
throw new Error("Hex string must have even length");
}
// Validate characters
if (!/^[0-9a-f]*$/.test(cleaned)) {
throw new Error("Hex string contains invalid characters");
}
return Buffer.from(cleaned, "hex");
}
// Usage
try {
const buffer = safeHexToBuffer("1a2b3c");
console.log("Success:", buffer);
} catch (err) {
console.error("Invalid hex:", err.message);
}If receiving hex strings from external sources (APIs, files), debug the raw input:
const fromAPI = '"1a2b3c"'; // With quotes
const rawData = fromAPI.slice(1, -1); // Remove quotes
console.log("Raw data length:", rawData.length);
console.log("Raw data:", JSON.stringify(rawData));
console.log("Character codes:", [...rawData].map(c => c.charCodeAt(0)));
const buffer = Buffer.from(rawData, "hex");Common issues:
- JSON-parsed strings still contain escaped characters
- API responses wrapped in quotes or brackets
- Unicode normalization changing character count
- Hidden whitespace or BOM markers
Advanced notes
Node.js versions have inconsistent behavior with invalid hex strings. Older versions (pre-7.0) would silently ignore invalid characters and return partial buffers, while newer versions may throw TypeErrors. The safest approach is to validate input before conversion rather than relying on error handling. If processing large amounts of hex data, consider using regex-based validation or a hex validation library. For cryptographic operations with hex keys, always implement strict validation to prevent security issues from silently corrupted keys.
Frequently asked questions
- What does "ERR_INVALID_HEX_STRING" mean?
- from() or the deprecated new Buffer() constructor with invalid hex data. The error specifically indicates that the provided string either has an odd number of characters (each hex byte requires exactly 2 characters) or contains non-hexadecimal characters. Hexadecimal strings must consist exclusively of valid hex digits (0-9, a-f, A-F) with an even count for proper byte pairing.
- How do I fix "ERR_INVALID_HEX_STRING"?
- This error occurs when attempting to create a Buffer with a malformed hexadecimal string. The hex string must contain an even number of valid hexadecimal characters, with each pair representing a single byte.
- What causes "ERR_INVALID_HEX_STRING"?
- Hex string has an odd number of characters (e.g., '1a2' instead of '1a2b') String contains non-hexadecimal characters (e.g., spaces, letters outside a-f, special characters) Trimming operations added/removed characters changing string length parity
- Is the "ERR_INVALID_HEX_STRING" 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 Buffer API - Hex Encoding(Official Docs)
- ๐
- ๐
- ๐