How to Base64 Decode a String
Learn how to decode Base64-encoded strings back to plain text. Includes examples, error handling tips, and common pitfalls when decoding Base64 data.
Detailed Explanation
Base64 decoding is the reverse of encoding: it takes a Base64-encoded string and converts it back to the original bytes, which can then be interpreted as text, an image, or any other data format.
The decoding process:
- Take the Base64 string, for example
"SGVsbG8=". - Remove any padding characters (
=) and note how many there were (this tells you how many bytes to discard at the end). - Map each Base64 character back to its 6-bit value using the Base64 alphabet:
S=18,G=6,V=21,s=44,b=27,G=6,8=60. - Concatenate all the 6-bit values into a continuous bit stream.
- Split the bit stream into 8-bit bytes.
- Convert each byte back to its character:
72=H,101=e,108=l,108=l,111=o.
In JavaScript:
const decoded = atob("SGVsbG8sIFdvcmxkIQ==");
// Result: "Hello, World!"
Error handling is critical. A Base64 string can only contain characters from the Base64 alphabet (A-Z, a-z, 0-9, +, /, and = for padding). If you pass a string with invalid characters to a decoder, it will throw an error. Always wrap decoding in a try-catch block:
try {
const result = atob(input);
} catch (e) {
console.error("Invalid Base64 input");
}
Common pitfalls:
- Forgetting that the decoded output is raw bytes, not necessarily valid text. If the original data was an image or binary file, interpreting it as a string will produce garbage.
- Confusing URL-safe Base64 (
-and_) with standard Base64 (+and/). Theatob()function expects standard Base64 and will fail on URL-safe variants unless you replace the characters first. - Whitespace or line breaks in the input can cause decoding failures in strict parsers, though many implementations silently ignore them.
Use Case
Decoding a Base64-encoded configuration payload received from an API response, such as Kubernetes Secrets which store values as Base64-encoded strings.