Short answer: decode the model response exactly once, validate the PNG bytes before upload, and send those bytes to a presigned S3-compatible URL instead of pushing them through your application server. Most “malformed base64” failures are boundary mistakes: a data-URL prefix was left in place, a URL-safe alphabet was treated as standard base64, or text was uploaded where binary was expected.
I care about this because an image pipeline can look healthy while quietly producing unusable objects. A 200 from the generation step proves very little. The useful question is whether the object has the expected magic bytes, length, content type, and checksum after the upload. That is the experiment constraint here: prove the bytes at each boundary, then measure throughput and retry behavior before committing to a storage layout.
How should image generation save bytes to compatible object storage?
Treat the model response as an untrusted representation, not as an image. Some APIs return a plain base64 string; others return a data URL such as data:image/png;base64,...; a URL-safe variant may replace + and / with - and _. Passing any of those forms directly to Buffer.from(value, "base64") can yield a buffer that exists but is not the PNG you intended.
The first gate is normalization. Remove only a recognized data-URL header, reject unexpected media types, restore padding when the input is an unpadded base64 string, and refuse characters outside the selected alphabet. Do not “repair” arbitrary garbage by deleting characters. That turns a useful failure into a corrupted asset.
The second gate is the PNG signature. A PNG starts with eight fixed bytes: 89 50 4e 47 0d 0a 1a 0a. This check is cheap and catches a surprising number of cases where an error message, JSON wrapper, or HTML response was decoded as if it were an image.
Bytes first.
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); function decodePng(input: string): Buffer { const value = input.trim(); const match = value.match(/^data:([^;,]+);base64,(.*)$/s); const mediaType = match?.[1] ?? "image/png"; let encoded = match?.[2] ?? value; if (mediaType !== "image/png") { throw new Error(`expected image/png, got ${mediaType}`); } if (!/^[A-Za-z0-9+/_-]*={0,2}$/.test(encoded)) { throw new Error("base64 contains characters outside the accepted alphabet"); } encoded = encoded.replace(/-/g, "+").replace(/_/g, "/"); encoded += "=".repeat((4 - (encoded.length % 4)) % 4); if (encoded.length % 4 !== 0) throw new Error("base64 length is invalid"); const bytes = Buffer.from(encoded, "base64"); if (bytes.length < PNG_SIGNATURE.length || !bytes.subarray(0, 8).equals(PNG_SIGNATURE)) { throw new Error("decoded bytes are not a PNG"); } return bytes; } This is intentionally strict. It is better to discard one bad generation and record why than to create an object that downstream thumbnailers cannot parse. I once spent an afternoon tracing a “storage corruption” report that was actually a serialized object with a data: prefix decoded twice. The object was non-empty, so the upload metric looked fine. The signature check would have stopped it at the first boundary. The investigation also exposed a second trap: our retry worker logged only the final HTTP status, so the original decode exception disappeared behind three identical upload attempts. I now attach a failure stage, encoded length, decoded length, and a request correlation ID to every job, while deliberately excluding the image payload and presigned URL. That makes a malformed response distinguishable from a rejected write without putting sensitive material in logs.
How does a direct upload avoid proxying generated PNG bytes?
After validation, ask your storage service for a presigned PUT URL and upload the Buffer directly. Your API handles authorization and metadata; the large body travels from the worker to object storage. That distinction matters for generated media because a 20 MB image multiplied by concurrent jobs can exhaust application memory and inflate egress through the control plane.
async function putPng(url: string, bytes: Buffer): Promise<void> { const response = await fetch(url, { method: "PUT", headers: { "content-type": "image/png", "content-length": String(bytes.length), }, body: bytes, }); if (!response.ok) { throw new Error(`object upload failed with status ${response.status}`); } } const png = decodePng(modelResponseImage); await putPng(presignedPutUrl, png); Keep the presigned URL short-lived and scoped to one object key. Do not log it. Store the byte length and a digest alongside the job record, then verify the object with a metadata request or a read-after-write check appropriate to your storage consistency model. A successful HTTP response is transport evidence, not proof that the right bytes were addressed.
For browser uploads, progress belongs on the client boundary. XMLHttpRequest exposes upload progress events, while a server-side worker can report bytes sent from its own HTTP client. Either way, report loaded and total as telemetry rather than putting progress fields into the image payload. The MDN example is useful here because it keeps progress separate from the request body.
Where do malformed base64 errors actually originate?
I use a small failure taxonomy in logs. It keeps retries from hiding the original defect.
| Boundary | Typical symptom | Check to record |
|---|---|---|
| Model response | Decoder rejects input or yields tiny bytes | prefix, alphabet, encoded length |
| Node.js conversion | Buffer exists but is not an image | PNG signature and byte length |
| Presigned request | Upload is rejected or object has wrong metadata | status, content type, key, digest |
| Consumer read | Thumbnailer cannot parse the object | stored digest and first eight bytes |
Never retry a deterministic decode failure. Retry a transient transport failure with a bounded budget and an idempotent object key. A retry loop around Buffer.from only burns worker time; it cannot make malformed input valid. Conversely, retrying a PUT with a new random key can leave orphaned objects, so derive the key from the generation job and revision.
The long-running cost is retention. Generated previews are often disposable, while the original may need a longer legal or product lifetime. Lifecycle rules can expire temporary prefixes and transition older objects without a cleanup worker scanning every key. AWS documents this pattern in its object lifecycle guidance, and the same concept exists across S3-compatible implementations. Put the retention decision in the object key or metadata at creation time; do not infer it later from a filename.
What should you measure before choosing an upload architecture?
Run a fixed batch of representative images, including the largest expected PNG and deliberately malformed responses. Measure end-to-end latency, peak worker memory, direct-upload throughput, retry count, and the percentage of objects whose stored digest matches the decoded buffer. Large-file throughput is the primary axis for this scenario, but correctness is a release gate.
The simple architecture—decode and proxy through the app—can be fine for tiny thumbnails or a local prototype. The catch is that it is not suitable when concurrent generations can fill the app's memory or when bandwidth is metered at the application tier. Use direct presigned uploads when the body is large and the app only needs to authorize, observe, and record the write. Stick with a proxy when you need synchronous content transformation that storage cannot perform, and accept the throughput ceiling deliberately.
I’m not sure every storage provider exposes identical checksum headers or consistency guarantees, so make those assumptions explicit in your adapter and test them against the target service. The portable part is the discipline: one decode, one signature check, one bounded upload, and a recorded digest.
References
- AWS S3 object lifecycle management: https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html
- MDN, Using XMLHttpRequest and upload progress events: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest
- PNG specification, signature and chunk structure: https://www.w3.org/TR/PNG/
