---
title: "Base64"
description: "RFC 4648 base64 with + and / or the URL alphabet. Three bytes as four characters padded with = and line breaks skipped on decode"
canonical_url: "https://encodings.agntn.dev/encodings/base64"
---
# Base64

> RFC 4648 base64 with + and / or the URL alphabet. Three bytes as four characters padded with = and line breaks skipped on decode

<encoding-facts name="base64">



</encoding-facts>

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.


## Sitemap

See the full [sitemap](https://encodings.agntn.dev/sitemap.md) for all pages.
