How to Decode Base64 in Python and JavaScript

A Base64 decoder first gives you bytes. What you do next depends on what was encoded. Try 5L2g5aW9 in the online Base64 decoder. The six output bytes are e4 bd a0 e5 a5 bd. Read them as UTF-8 and they spell 你好. The examples below use those bytes so you can check the same result in each runtime.

Decode Base64 in Python with validation

Use base64.b64decode with validate=True when your input is a standard Base64 field. With the default settings, Python can discard characters outside the alphabet. Strict validation makes a stray punctuation mark or invalid padding an error. A MIME attachment body may have intentional CRLF line endings. The first example removes only carriage returns and line feeds before validation. Keep that step out if the field is required to be a single line. Copy just the encoded attachment body, excluding mail headers and boundary markers.

import base64
import binascii

wrapped = "5L2g\r\n5aW9"
value = wrapped.replace("\r", "").replace("\n", "")
try:
    raw = base64.b64decode(value, validate=True)
except binascii.Error as exc:
    raise ValueError("Invalid standard Base64") from exc

print(raw.hex(" "))       # e4 bd a0 e5 a5 bd
print(raw.decode("utf-8"))  # 你好

A successful decode proves that this input can be read as Base64. A truncated string can still pass validation if it ends on a complete group. To check a file transfer, compare the output length and, when available, the checksum with the sender’s copy. For an image, PDF or archive, write the bytes directly with Path("output.bin").write_bytes(raw) after importing Path from pathlib.

Python and URL-safe values

A URL-safe field can use a hyphen and an underscore, and its format may omit the trailing padding. For a known, well-formed unpadded value, set s = "-_8" and run base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)).hex(). The result is fbff. Those are two binary bytes. The new equals sign supplies padding, not missing file contents. A leftover length of one modulo four is invalid. If you need to reject malformed URL-safe fields, check the permitted alphabet and padding for that field before decoding. You can compare an individual value in the Base64URL decoder.

Decode Base64 in browser JavaScript

In a browser, atob reads a standard Base64 string. Each character in its return value carries one byte. Printing that intermediate string directly can make Chinese text look garbled. Build a byte array, then tell the text decoder which character set produced those bytes. Run this example in a browser console.

const encoded = "5L2g5aW9";
const binary = atob(encoded);
const bytes = Uint8Array.from(binary, ch => ch.charCodeAt(0));
const decoder = new TextDecoder("utf-8", { fatal: true });
console.log(bytes.length);          // 6
console.log(decoder.decode(bytes)); // 你好

An invalid Base64 input can cause atob to throw InvalidCharacterError. A failure in the subsequent text conversion points to a different problem. The bytes may belong to a different character set or to a binary file. Use the charset declared by the source system. For example, a legacy Chinese export may use GB18030. If the recovered text is JSON, the JSON view lets you inspect the original spelling and indentation before you parse it.

Decode Base64 in Node.js with Buffer

Node.js can return the bytes directly with Buffer.from(value, "base64"). A Buffer can be passed to a text decoder, written to disk, or compared with another buffer. This example assumes a trusted, well-formed Base64 string and shows both the byte representation and the text. Run it in Node.js.

const { Buffer } = require("node:buffer");
const { TextDecoder } = require("node:util");

const raw = Buffer.from("5L2g5aW9", "base64");
console.log(raw.toString("hex"));   // e4bda0e5a5bd
console.log(new TextDecoder("utf-8", { fatal: true }).decode(raw)); // 你好

Node’s Base64 reader accepts whitespace and the URL-safe alphabet. A Buffer result alone does not tell you whether the input satisfies a protocol that requires canonical standard Base64. For a field that requires the padded standard form with no whitespace, re-encode the buffer with raw.toString("base64") and compare it with the original string. Apply the rules of the field you are reading before accepting the value.