Base64 in JavaScript

Base64 writes bytes as ASCII text. The base64 js functions do that conversion in the browser and in Node.js, so a binary value can sit in a JSON string, a data URL, or an HTTP header.

What base64 is

RFC 4648 defines the alphabet. It is A through Z, a through z, 0 through 9, +, and /. That is 64 characters. = is a 65th character used only as padding.

The encoder takes three input bytes, 24 bits, and splits them into four groups of six bits. Each group is an index into that alphabet. When the input length is a multiple of three, the output length is four characters for every three bytes, so the text is one third longer than the byte count. A final one-byte group becomes two characters and ==. A final two-byte group becomes three characters and =.

btoa("f");      // "Zg=="
btoa("fo");     // "Zm8="
btoa("foo");    // "Zm9v"
btoa("foobar"); // "Zm9vYmFy"

btoa("f") reads the one character f as the byte 0x66. One byte is an 8-bit final group, so the result is two alphabet characters and ==. "fo" is two bytes, so the result ends in one =. "foo" is three bytes and needs no padding. "foobar" is six bytes, two full groups, and the result is the RFC 4648 test vector Zm9vYmFy.

You use the same encoding when an <img> src is a base64 data URL, when a JSON body has to carry bytes, and when an email body uses the MIME base64 content-transfer encoding. MIME also wraps lines at 76 characters. RFC 4648 itself does not add those line breaks. HTTP Basic authentication is the user id, a colon, and the password, encoded with this alphabet. The URL-safe variant, below, is the one that belongs in a query string.

btoa() and atob()

btoa() encodes a binary string. atob() decodes one. In the browser they are on Window. In Node.js they have been globals since 16.0.0, as aliases of buffer.btoa and buffer.atob. Node.js marks both Stability 3, Legacy, and the buffer docs tell you to use Buffer in new server code.

A binary string here means each character is one byte. The code point has to be in the range U+0000 to U+00FF. JavaScript strings are UTF-16, so this is a smaller set than a normal string.

const encoded = btoa("Hello, world");
const decoded = atob(encoded);

btoa reads "Hello, world" as 12 bytes and returns "SGVsbG8sIHdvcmxk". atob reads that alphabet text and returns "Hello, world".

btoa does not read a Uint8Array as bytes. The value is turned into a string first. String(new Uint8Array([104, 101, 108, 108, 111])) is "104,101,108,108,111", and btoa of that array returns "MTA0LDEwMSwxMDgsMTA4LDExMQ==".

Unicode

btoa throws if any code point is above U+00FF. Emoji, CJK characters, and many accented letters hit that limit.

btoa("文");

That call throws an InvalidCharacterError DOMException. The message in Node.js 22 is "Invalid character". The character 文 is U+6587, which does not fit in one byte, so btoa never looks at a UTF-8 encoding of it.

Encode the string to UTF-8 bytes first, then turn those bytes into a binary string:

function bytesToBase64(bytes) {
  const binString = Array.from(bytes, (byte) => String.fromCodePoint(byte)).join("");
  return btoa(binString);
}

function base64ToBytes(base64) {
  const binString = atob(base64);
  return Uint8Array.from(binString, (char) => char.codePointAt(0));
}

const encoded = bytesToBase64(new TextEncoder().encode("a Ā 文"));
const text = new TextDecoder().decode(base64ToBytes(encoded));

TextEncoder encodes "a Ā 文" as UTF-8 bytes. bytesToBase64 builds a string where each character’s code point is one of those byte values, and btoa encodes that string. encoded is "YSDEgCDmloc=". atob returns the binary string, base64ToBytes copies each code point into a Uint8Array, and TextDecoder turns those UTF-8 bytes back into "a Ā 文".

Uint8Array toBase64()

Uint8Array can encode and decode base64 without a binary string. toBase64() reads the bytes in the array and returns a string. Uint8Array.fromBase64() builds a new array from a string. setFromBase64() writes into an array you already allocated and returns { read, written }.

MDN marks the three methods Baseline Newly available since September 2025. They are in Chrome 140, Edge 140, Firefox 133, and Safari 18.2. Node.js 25.0.0 added them with V8 14.1. Node.js 22.23.4 does not have them: Uint8Array.prototype.toBase64 is undefined there. Check before you call.

if (typeof Uint8Array.prototype.toBase64 === "function") {
  const bytes = new Uint8Array([29, 233, 101, 161]);
  bytes.toBase64(); // "HelloQ=="
  bytes.toBase64({ omitPadding: true }); // "HelloQ"
  bytes.toBase64({ alphabet: "base64url" });
}

alphabet is "base64" by default, which uses + and /. "base64url" uses - and _. omitPadding defaults to false. A wrong alphabet throws TypeError.

fromBase64 ignores ASCII whitespace. Its default lastChunkHandling is "loose", so a final group shorter than four characters can still decode, and extra bits in that last character are discarded. "strict" requires a final group of four characters with = padding, and those extra bits have to be zero. "stop-before-partial" ignores an incomplete final group. A character outside the chosen alphabet throws SyntaxError.

setFromBase64 starts writing at index 0. read is how many characters of the input it consumed, including padding and whitespace when the decoded bytes fit. written is how many bytes it stored, and it never exceeds the array’s length. To write at an offset, call it on array.subarray(offset).

Buffer in Node.js

Buffer is the Node.js API for this. Buffer.from(string) uses UTF-8 when you omit the encoding. toString("base64") encodes those bytes.

const encoded = Buffer.from("hello world").toString("base64");
const text = Buffer.from(encoded, "base64").toString("utf8");

encoded is "aGVsbG8gd29ybGQ=". The second line reads that text as base64 and decodes the bytes as UTF-8, so text is "hello world".

"base64url" is the URL-safe alphabet, and encoding with it omits padding. Buffer.from("hello world").toString("base64url") is "aGVsbG8gd29ybGQ". Decoding with "base64" also accepts the URL-safe alphabet, and it ignores spaces, tabs, and newlines. Decoding with "base64url" also accepts ordinary base64, including padding.

Buffer.from("文") does not throw. It encodes the character as UTF-8 first, so the base64 is the UTF-8 bytes. btoa("文") throws, because it never takes that step. That is the practical split. Browser btoa wants a Latin-1 string. Buffer wants text or bytes, and it names the encoding.

URL-safe base64

+, /, and = are awkward in a URL. + is a space in the application/x-www-form-urlencoded rules, / splits a path, and = is padding that is often percent-encoded. RFC 4648 section 5 names the URL and filename safe alphabet base64url. Index 62 is - and index 63 is _.

A compact JWS uses that alphabet and also drops the = characters. If you only have btoa, replace the characters after encoding:

function toBase64Url(bytes) {
  const bin = Array.from(bytes, (byte) => String.fromCodePoint(byte)).join("");
  return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
}

function fromBase64Url(value) {
  const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
  const bin = atob(base64);
  return Uint8Array.from(bin, (char) => char.codePointAt(0));
}

const encoded = toBase64Url(Uint8Array.from([251, 255]));
const bytes = fromBase64Url(encoded);

The input bytes are 0xFB and 0xFF. Standard base64 for those bytes is +/8=. toBase64Url encodes with btoa, then replaces + with -, / with _, and strips =, so encoded is "-_8". fromBase64Url puts + and / back. atob accepts the missing padding here, because the length is not 1 mod 4, and the returned bytes are [251, 255].

atob does not accept - or _. atob("-_8") throws InvalidCharacterError. On Node.js, Buffer.from(bytes).toString("base64url") does the same replacement and padding strip in one call. Uint8Array.prototype.toBase64({ alphabet: "base64url", omitPadding: true }) is the same option pair where that method exists.

base64-js and js-base64

Two packages show up when you search for a library. Both are pure JavaScript and have no dependencies. You do not need either one when btoa, Buffer, or Uint8Array.toBase64 already covers the call.

base64-js 1.5.1 converts between a Uint8Array and a standard base64 string. The published base64js.min.js in that version is 2192 bytes.

import { fromByteArray, toByteArray } from "base64-js";

const encoded = fromByteArray(new Uint8Array([104, 101, 108, 108, 111]));
const bytes = toByteArray(encoded);

fromByteArray returns "aGVsbG8=". toByteArray returns a Uint8Array of those five bytes, which are the letters in "hello". The npm package buffer (the browser port of Node’s Buffer, version 6.0.3) depends on base64-js. Node’s built-in Buffer does not.

js-base64 3.9.7 encodes and decodes UTF-8 strings, bytes, and the URL-safe alphabet. The package is written in TypeScript and ships base64.d.ts. The published base64.mjs in 3.9.7 is 10017 bytes.

import { Base64 } from "js-base64";

Base64.encode("小飼弾");       // "5bCP6aO85by+"
Base64.encodeURI("小飼弾");    // "5bCP6aO85by-"
Base64.decode("5bCP6aO85by-"); // "小飼弾"

Base64.encode treats the argument as UTF-8 text and returns standard base64. The second argument true, and Base64.encodeURI, switch to the URL-safe alphabet and omit padding. Base64.decode accepts either alphabet, with or without padding, and returns a UTF-8 string. Base64.btoa("小飼弾") throws InvalidCharacterError, the same limit as the platform btoa. For bytes, Base64.fromUint8Array encodes and Base64.toUint8Array decodes. Base64.fromUint8Array(Uint8Array.from([251, 255])) is "+/8=", and the second argument true makes it "-_8".

Use btoa when the string is already one byte per character and you do not want a dependency. Use Buffer in Node.js. Use toBase64 when the runtime has it and you already hold a Uint8Array. Use base64-js when you need that Uint8Array conversion on an older runtime and you do not want the string helpers. Use js-base64 when you want UTF-8 text and URL-safe output from one API on a runtime that still lacks Uint8Array.toBase64.

Files, fetch, and a JWT payload

FileReader.readAsDataURL(file) does not return the base64 by itself. It returns undefined, and the load event fires when reader.result is set. That result is a data URL, not the bare alphabet text. The prefix looks like data:image/png;base64,, and the base64 starts after the comma.

const reader = new FileReader();
reader.addEventListener("load", () => {
  const dataUrl = reader.result;
  const base64 = String(dataUrl).split(",")[1];
});
reader.readAsDataURL(file);

readAsDataURL starts reading file. On load, dataUrl is the whole data: URL, and split(",")[1] is the base64 segment. You can assign dataUrl straight to an image’s src.

To turn base64 back into a file the browser can download, decode to bytes, wrap a Blob, and make an object URL:

const bytes = base64ToBytes(base64);
const blob = new Blob([bytes], { type: "application/pdf" });
const url = URL.createObjectURL(blob);

base64ToBytes is the function from the Unicode section. new Blob copies those bytes into a blob with that media type. URL.createObjectURL returns a blob: URL for an <a href> or for fetch. Call URL.revokeObjectURL when you are done with it.

A JSON API that wants the file as text looks like this:

await fetch("/upload", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ file: base64 }),
});

JSON.stringify puts the base64 string into the body. That string uses four characters for every three file bytes, and a short final group is padded so the character count is still a multiple of four. fetch can send the File or Blob itself when the endpoint accepts the raw body or multipart/form-data, and then you do not pay for the alphabet expansion.

A JWT in compact form is a JWS. RFC 7515 defines the header and the payload as base64url with the = characters removed, joined by ., and the third segment is the signature over the first two. Decoding the middle segment shows the JSON. It does not check the signature.

const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjMifQ.signature";
const payloadPart = token.split(".")[1].replaceAll("-", "+").replaceAll("_", "/");
const payload = JSON.parse(atob(payloadPart));

split(".")[1] is eyJzdWIiOiIxMjMifQ. That string has no - or _, so the replacements change nothing. atob returns '{"sub":"123"}', and JSON.parse returns { sub: "123" }. The header segment decodes to {"alg":"HS256","typ":"JWT"}. The third segment in this token is the placeholder signature. It is not a MAC of the first two segments, and this code never looks at it. A real token still has to be verified with the algorithm and key the issuer used.

Errors and padding

btoa throws InvalidCharacterError when a code point is above U+00FF. atob throws the same name when the input is not valid base64. atob follows the HTML forgiving-base64 decode. It removes ASCII whitespace first, so a MIME body with 76-character lines still decodes. atob("Zm9v\r\nYmFy") is "foobar". If the length after that is a multiple of four and the string ends in one or two = characters, those are removed. If the length mod 4 is 1, decoding fails. atob("Y") throws. Any character other than +, /, and an ASCII letter or digit also fails, which is why - and _ fail.

atob("YQ") and atob("YQ==") both return "a". The missing padding is allowed. atob("YR") also returns "a", because the decoder discards the leftover bits of the last character. A strict decoder is allowed to reject that. Uint8Array.fromBase64("YR", { lastChunkHandling: "strict" }) throws SyntaxError where the method exists.

function decodeOrNull(value) {
  try {
    return atob(value);
  } catch (error) {
    if (error.name === "InvalidCharacterError") {
      return null;
    }
    throw error;
  }
}

decodeOrNull("YQ==") returns "a". decodeOrNull("@@@") hits the catch, sees InvalidCharacterError, and returns null. Any other error is rethrown.

Base64 is not encryption

RFC 4648 says base encoding hides text visually and does not provide confidentiality. Anyone who has the string can reverse it. Basic authentication in RFC 7617 is that kind of encoding. With UTF-8, the user id test, a colon, the password 123£, and then base64, is the header value the RFC prints:

Buffer.from("test:123£").toString("base64"); // "dGVzdDoxMjPCow=="

Buffer.from encodes "test:123£" as UTF-8. Those bytes are 74 65 73 74 3a 31 32 33 c2 a3. toString("base64") returns "dGVzdDoxMjPCow==". The Authorization header is Basic plus that string. Anyone who can see the header can decode the password.

The same limit applies to a JWT payload. The signature can stop someone from changing the payload without detection. It does not stop them from reading it. Do not put a password or an API key in the payload and treat the token as secret storage.

If the decoded string is text you want to show, assign it to textContent. If you assign it to innerHTML, the browser parses tags in that string. Base64 is not a sanitizer, and decoding it does not make the contents safe to insert as HTML.

A long encode on the main thread blocks input and painting until it returns. The same functions can run in a worker. For a large file, keep the Blob or the Uint8Array and send that, instead of a second copy that uses four characters for every three bytes.

If this article was helpful, tweet it!