Encode and decode base64 data
Prefer Uint8Array.prototype.toBase64() and Uint8Array.fromBase64() for encoding and decoding base64 data in Bun. These APIs work directly with bytes, so they are a better fit for binary data than the older btoa() and atob() globals.
TypeScript
const bytes = new Uint8Array([98, 117, 110]);
const encoded = bytes.toBase64(); // => "YnVu"
const decoded = Uint8Array.fromBase64(encoded);
// => Uint8Array(3) [ 98, 117, 110 ]
For strings, convert to and from UTF-8 bytes with TextEncoder and TextDecoder.
TypeScript
const bytes = new TextEncoder().encode("hello world");
const encoded = bytes.toBase64(); // => "aGVsbG8gd29ybGQ="
const decoded = Uint8Array.fromBase64(encoded);
const text = new TextDecoder().decode(decoded); // => "hello world"
Node.js Buffer extends Uint8Array, so you can encode buffers with toBase64() and pass them to APIs that accept Uint8Array. Buffer also provides Node.js-compatible base64 decoding with Buffer.from(encoded, "base64").
TypeScript
const encoded = Buffer.from("hello world").toBase64();
// => "aGVsbG8gd29ybGQ="
const bytes = Buffer.from(encoded, "base64");
bytes instanceof Uint8Array; // => true
const text = bytes.toString("utf8");
// => "hello world"
See Web APIs.