Encodings

Base64

RFC 4648 base64 with + and / or the URL alphabet. Three bytes as four characters padded with = and line breaks skipped on decode
IDbase6409 / 20base64 · 64 characters
Encoding / Base64

Base64

Three bytes as four characters. MIME, data URLs, PEM.

Overhead
+33% on random bytes
Padding
= to a whole block
Standard
RFC 4648 §4 and §5
Family
1 in base64
family 1 / 20

Sample

Out
aGVsbG8gd29ybGQh
Back
"hello world!"

Options

alphabetstring
default standard
standard (+ and /) or url (- and _, safe in URLs and file names)
paddingboolean
default true
Pad the last block with = to four characters
canonicalboolean
default false
Refuse non-zero spare bits in the last character; case, whitespace and padding read as usual

Access

Importimport { base64 } from "@agntn/encodings/base64"
CLIencodings encode base64 'hello world!'
Tryplayground with the sample above

The one you've seen a million times. Three bytes, four characters, = to fill the last block.

ts
encode("base64", "hello world!");             // "aGVsbG8gd29ybGQh"
decode("base64", "aGVsbG8g\r\nd29ybGQh").bytes;  // "hello world!", line break and all skipped

Decoding skips whitespace, so a MIME body or a PEM block decodes as it is. It takes the text without padding too. The wrong padding, though? Zg= is one = short, and you'll hear about it. A - or _ is an error here, not a guess.

Is YR== valid base64?

Depends who you ask. a is eight bits, YR is twelve, and the four spare bits should be zero. R sets one of them. Decoding shrugs and reads a, same as YQ==. RFC 4648 lets a decoder go either way.

Want the strict answer? canonical: true refuses it and names the character:

ts
decode("base64", "YR==", { canonical: true });
// DecodeError: "R" (U+0052) at index 1 leaves non-zero bits after the last byte

It looks at those bits only, so line breaks and missing padding still pass. The URL alphabet takes it too.

The URL alphabet

+ and / break a URL and a file name. RFC 4648 swaps them for - and _, and alphabet: "url" does the same. JWTs drop the padding on top of that:

ts
encode("base64", '{"alg":"HS256","typ":"JWT"}', { alphabet: "url", padding: false });
// "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"

Look familiar? Every JWT starts with eyJ, because every JWT starts with {". To read one back, pass the alphabet to decode as well. It takes the padding when it's there.