ERR_BUFFER_OUT_OF_BOUNDS
Attempted to access bytes outside the bounds of a Buffer.
Usually happens because:
- ☑ Offset Overflow
- ☑ Overwriting Buffer Bounds
🔍 Quick Checklist:
What is ERR_BUFFER_OUT_OF_BOUNDS?
The ERR_BUFFER_OUT_OF_BOUNDS error is thrown by Node.js Buffer APIs when an operation attempts to read or write bytes at an offset index that is outside the allocated memory size of the target Buffer.
Common Causes
- Offset Overflow: Accessing index values larger than the Buffer's length.
- Overwriting Buffer Bounds: Writing bytes that exceed static buffer slices allocations.
| Cause | Frequency |
|---|---|
| Offset Overflow | ⭐⭐⭐⭐⭐ |
| Overwriting Buffer Bounds | ⭐⭐⭐⭐ |
Common Mistakes
- Assuming Buffer allocations resize automatically (Buffer allocations are static in size; use Buffer.concat() to grow them).
How to Fix
Framework-Specific Examples
Checking buffer size bounds before running offsets parse routines.
const parseBinary = (buf) => {
if (buf.length < 4) {
throw new Error('Payload too small');
}
return buf.readInt32BE(0);
};Server Configuration Examples
Checking buffers.
# Handled at application layerBest Practices
- Validate reading index positions against the Buffer.length property dynamically.
Frequently Asked Questions (FAQ)
Q: What is the difference between Buffer.alloc() and Buffer.allocUnsafe()?
Buffer.alloc() initializes memory to zero. Buffer.allocUnsafe() does not, making it faster but potentially leaking sensitive remnants of old files or sessions if read out of bounds.
Q: How do I grow a Buffer dynamically?
Buffers have a fixed size. To expand them, create a new larger Buffer and use `Buffer.concat([oldBuf, newChunks])`.
Q: Is this error a RangeError?
Yes. It inherits from the built-in JavaScript `RangeError` class.
Q: What is the safest way to read multi-byte values?
Ensure `index + byteSize <= buffer.length` before executing read calls (e.g. check offset + 4 when calling `readInt32BE(offset)`).