Base64 and base64url
Server-side JavaScript has the standard base64 functions, so the same code works in a browser and on the server.
When to use
Use these whenever bytes travel as text: a WebAuthn credential ID or signature sent as base64url, a key stored in a document, or a value in a JSON Web Token.
Syntax
btoa(binaryString) // bytes as a string of characters U+0000 to U+00FF, to base64
atob(base64) // base64 to a binary string
Uint8Array.fromBase64(text, options) // base64 or base64url to a Uint8Array
bytes.toBase64(options) // a Uint8Array to base64 or base64url
fromBase64 options:
| Option | Values | Default |
|---|---|---|
alphabet |
"base64" (with + and /) or "base64url" (with - and _) |
"base64" |
lastChunkHandling |
"loose": decode a final group of 2 or 3 characters with or without = padding. "strict": require padding and no stray bits. "stop-before-partial": leave a final partial group undecoded |
"loose" |
toBase64 options:
| Option | Values | Default |
|---|---|---|
alphabet |
"base64" or "base64url" |
"base64" |
omitPadding |
true to leave off the = padding |
false |
Spaces, tabs, line feeds, form feeds and carriage returns in the input are ignored.
Uint8Array.fromHex, toHex, setFromBase64 and setFromHex are not available.
Examples
Decode a base64url credential ID from a request, and encode bytes for storage:
const id = Uint8Array.fromBase64(credentialId, {alphabet: "base64url"});
const text = id.toBase64({alphabet: "base64url", omitPadding: true});
Encode and decode text with btoa and atob:
btoa("foobar"); // "Zm9vYmFy"
atob("Zm9vYmFy"); // "foobar"
btoa works on characters, not bytes. To encode UTF-8 text, encode it to bytes first: new TextEncoder().encode(text).toBase64().
Error cases
| What happened | Error |
|---|---|
atob given something that is not base64, including a lone surrogate |
DOMException named InvalidCharacterError |
btoa given a character above U+00FF, including a lone surrogate |
DOMException named InvalidCharacterError |
atob or btoa called with no argument |
TypeError |
fromBase64 given malformed input, a character from the other alphabet, a lone surrogate, or (when strict) a missing pad or stray bits |
SyntaxError |
fromBase64 given something other than a string, or an unknown option value |
TypeError |
fromBase64 or toBase64 given options that are not an object, such as null or a string |
TypeError |
toBase64 called on something other than a Uint8Array |
TypeError |
toBase64 called on an array whose buffer has been detached, for example by ArrayBuffer.prototype.transfer |
TypeError |