Base64 decode in JavaScript: the short version
Browsers have a built-in atob function, but on its own it only handles plain ASCII. To get real text, including emoji and non-English letters, read the bytes with TextDecoder:
function decodeBase64(b64) {
const bytes = Uint8Array.from(atob(b64), c => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
decodeBase64("SGVsbG8sIHdvcmxkISDwn5GLIOS9oOWlvQ==");
// "Hello, world! 👋 你好"
atob returns a "binary string" with one character per byte. That looks fine for English, but a UTF-8 character such as 你 takes three bytes and comes out as three strange symbols. Converting to a Uint8Array and decoding with TextDecoder fixes it.
Decode URL-safe Base64 and JWTs
JWTs and many APIs use Base64URL, which writes - and _ instead of + and /. atob only knows the standard alphabet, so swap the characters first:
function decodeBase64Url(s) {
return decodeBase64(s.replace(/-/g, "+").replace(/_/g, "/"));
}
const payload = "eyJ1c2VyIjoiYWRhIiwicm9sZSI6ImFkbWluIn0";
JSON.parse(decodeBase64Url(payload)); // { user: "ada", role: "admin" }
You do not need to add = padding in the browser: atob accepts strings without it. For a whole JWT, split on . and decode the first two parts. The third part is a signature and is not readable text.
Base64 decode in Node.js
In Node.js, use Buffer. It works with bytes directly and understands both alphabets:
const text = Buffer.from(b64, "base64").toString("utf8");
// URL-safe input
const json = Buffer.from(payload, "base64url").toString("utf8");
// Save a decoded file
require("fs").writeFileSync("image.png", Buffer.from(b64, "base64"));
Unlike atob, Buffer.from does not throw on bad characters. It skips them and decodes what it can, so check the output if the input came from a user.
Turn Base64 into a downloadable file in the browser
When the data is an image or a PDF, build a Blob from the bytes instead of decoding to text:
const bytes = Uint8Array.from(atob(b64), c => c.charCodeAt(0));
const url = URL.createObjectURL(new Blob([bytes], { type: "image/png" }));
Use the URL as an <img> source or the href of a download link. Call URL.revokeObjectURL(url) when you are done with it.
Common JavaScript Base64 errors
InvalidCharacterError: The string to be decoded is not correctly encoded. The string contains a character outside the alphabet, often -, _, % or a quote, or its length shows it was cut off. Swap URL-safe characters, remove quotes, or check that you copied the whole value.
Garbled text such as é or ð. You used atob without TextDecoder. Apply the function above.
Check your result
Paste the same string into the Base64 decoder at the top of this page. If the tool shows the right text but your code does not, the issue is UTF-8 or alphabet handling. If the tool also rejects it, the input is broken.
For the same task in Python, see Base64 decode in Python. For everything else, use the online Base64 decoder.
Last updated: