0
0
JavascriptHow-ToBeginner · 3 min read

How to Decode Base64 in JavaScript: Simple Guide

To decode a base64 string in JavaScript, use the atob() function which converts base64 encoded data back to a normal string. For example, atob('SGVsbG8=') returns 'Hello'.
📐

Syntax

The basic syntax to decode a base64 string in JavaScript is:

  • atob(encodedString): Takes a base64 encoded string and returns the decoded string.

Note: The input must be a valid base64 encoded string.

javascript
const decoded = atob(encodedString);
💻

Example

This example shows how to decode a base64 encoded string and print the result.

javascript
const base64String = 'SGVsbG8gd29ybGQh';
const decodedString = atob(base64String);
console.log(decodedString);
Output
Hello world!
⚠️

Common Pitfalls

Common mistakes when decoding base64 in JavaScript include:

  • Passing a string that is not properly base64 encoded causes atob() to throw an error.
  • Trying to decode Unicode strings directly can produce incorrect results because atob() works with ASCII characters only.
  • Using atob() in Node.js requires a different approach since it is a browser API.

To decode Unicode strings, you need to convert the decoded ASCII string properly.

javascript
/* Wrong way: decoding Unicode base64 directly */
const base64Unicode = '5L2g5aW9'; // '你好' in base64
const wrong = atob(base64Unicode);
console.log(wrong); // garbled output

/* Right way: decode and convert to Unicode */
function decodeBase64Unicode(str) {
  return decodeURIComponent(
    atob(str)
      .split('')
      .map(c => '%'+('00'+c.charCodeAt(0).toString(16)).slice(-2))
      .join('')
  );
}
const correct = decodeBase64Unicode(base64Unicode);
console.log(correct); // 你好
Output
��� 你好
📊

Quick Reference

Summary tips for decoding base64 in JavaScript:

  • Use atob() for decoding base64 strings in browsers.
  • For Unicode strings, decode then convert using decodeURIComponent.
  • In Node.js, use Buffer.from(base64String, 'base64').toString('utf-8').

Key Takeaways

Use atob() to decode base64 strings in browser JavaScript.
For Unicode text, decode base64 then convert to proper characters to avoid garbled output.
Invalid base64 strings cause errors in atob().
In Node.js, use Buffer.from(...) instead of atob().
Always ensure your input is a valid base64 encoded string before decoding.