Avoid decoded-string allocation in z.base64() validation for large inputs
Summary
Could z.base64() validate large inputs without allocating a decoded copy of the string?
In Zod 4.6.5, isValidBase64() calls atob(data) and discards the result. A valid 32 MiB base64 string therefore temporarily produces a roughly 24 MiB decoded string even though validation returns the original input. This matters for multi-megabyte font/image payloads that will be decoded separately by their consumer.
This is an allocation-efficiency request, not a report of incorrect acceptance or a demonstrated OOM. I am not claiming the behavior was introduced in 4.6.
Environment
- Zod 4.6.5
- Node v24.13.0, macOS arm64
- The same
atob(data)call is present in current upstream source: schemas.ts at 10dda3a.
Standalone reproduction
Install [email protected], save the following as repro.mjs, and run node --expose-gc repro.mjs in a fresh process:
import { z } from 'zod';
const input = JSON.parse(JSON.stringify('A'.repeat(32 * 1024 * 1024)));
const schema = z.base64();
global.gc();
const before = process.memoryUsage().heapUsed;
const result = schema.safeParse(input);
const after = process.memoryUsage().heapUsed;
console.log({
node: process.version,
success: result.success,
inputMiB: input.length / 1024 ** 2,
heapDeltaMiB: (after - before) / 1024 ** 2,
});JSON round-tripping makes the synthetic input a materialized string before measurement; input construction is outside the measured interval.
Three fresh-process runs all returned success: true, inputMiB: 32, with heap deltas of 23.619, 23.618 and 23.837 MiB. These are before/after heap observations, not precise allocation profiling, retained memory or process peak RSS. GC timing can change the reported delta.
Desired behavior
Preserve the existing z.base64() API and strict alphabet/padding/whitespace semantics, but avoid a payload-sized decoded allocation solely to decide validity. Ideally validation would use bounded auxiliary memory and remain safe on multi-megabyte input.
I understand that atob() is fast and that a non-decoding implementation could trade CPU time for lower allocation; I would be happy to follow the maintainers' preferred approach rather than propose a new option or API prematurely.
Related: #4283 documents the older quantified-regex stack overflow, and #6534 fixes composed-pattern overflow while explicitly leaving parse-path memory unchanged. This request is about direct z.base64().safeParse() allocation, not reverting to the stack-overflow-prone grouped regex. I did not find an existing issue specifically covering that allocation.
Source: colinhacks/zod