Buffers Best Practices
Buffers are the right tool for small, known-size binary work - for everything else, cap sizes, prefer streams, and treat encoding and secrets explicitly.
Search across all documentation pages
Buffers are the right tool for small, known-size binary work - for everything else, cap sizes, prefer streams, and treat encoding and secrets explicitly.
readFile into one Buffer. Constant memory under load.MAX_FRAME or body size limits on binary parsers. Reject oversize length prefixes before allocation.Buffer.concat when total length is known. Avoid O(n²) realloc on many chunks.Buffer.alloc for secrets and crypto material. Not allocUnsafe unless immediately overwritten fully.utf8 explicitly in toString/from for text. Document legacy encodings in ADR if unavoidable.TextDecoder with fatal: true for inbound text protocols. Reject malformed sequences at boundary.Buffer.byteLength for UTF-8 size limits. Not string .length.crypto.timingSafeEqual on equal-length digests. No raw === on API keys.finally when feasible. buffer.fill(0) best-effort hygiene.data event equals one message.subarray over slice for zero-copy views. Copy when retaining beyond next read.TextEncoder/Uint8Array at fetch boundaries. Interop with browser clients.latin1 for "preservation". Explicit hex/base64 with size limits instead.Depends on API - typical REST 1-10 MB at reverse proxy and app. Stricter for auth endpoints.
Internal pooling of non-sensitive chunks you fully write before any read - never user-facing secrets.
Buffer extends Uint8Array - use either; prefer Web APIs at isomorphic boundaries.
Transfer ArrayBuffers to avoid copy - document ownership transfer semantics.
Decode UTF-8 to string first with fatal decoder - then parse - or limit size before decode.
Stream to disk or S3 - do not buffer entire file in RAM.
No - ${buf} coerces to string and may leak content in logs.
Split known frame across multiple feed() calls in node:test.
Only where schema stability and throughput justify complexity - not for one-off scripts.
Streams Best Practices for pipeline and backpressure rules.
Set bodyLimit and use streams for large downloads - Fastify defaults are not unlimited safety.
No at rest - use KMS/Vault. Base64 transport OK with TLS and short lifetime.
Stack versions: This page was written for Node.js 24.18.0 (Active LTS), npm 10+, TypeScript 5.6+, Express 5, Fastify 5, and NestJS 11.
Reviewed by Chris St. John·Last updated Jul 16, 2026