JavaScript Window atob() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Base64 decode

What You’ll Learn

The atob() method decodes Base64 text back into a readable string. This tutorial covers syntax, five worked examples, common mistakes (data URLs and JWTs), pairing with btoa(), and safe error handling.

01

Syntax

atob(encoded)

02

Input

Base64 string

03

Output

Binary / ASCII text

04

Pair

Inverse of btoa()

05

Data URLs

Strip prefix first

06

Errors

Invalid Base64 throws

Introduction

Base64 turns binary data into safe text using letters, digits, +, /, and padding =. Websites use it for data URLs, tokens, and API payloads. In the browser, window.atob() decodes that text back into a binary string—the reverse of btoa().

If someone encoded plain ASCII with btoa("Hello"), you can recover the original message with atob(). This guide walks through real patterns beginners encounter, including what not to pass directly into atob().

Understanding the atob() Method

atob stands for “ASCII to binary.” Despite the name, the return value is a JavaScript string where each character represents one byte (code points 0–255). For simple English text encoded with btoa(), the result looks like normal readable text.

Use atob() when you already have a valid Base64 payload and need the decoded bytes as a string. For Unicode beyond Latin-1, or for Node.js servers, you will need additional encoding steps or different APIs.

💡
Beginner Tip

Think of Base64 as a sealed envelope of text. btoa() puts your message inside; atob() opens it— but only if the envelope is valid Base64, not a full data: URL label.

📝 Syntax

General form of Window.atob():

JavaScript
window.atob(encodedString);
// shorthand (same in browsers):
atob(encodedString);

Parameters

  • encodedString — a Base64-encoded string. Must use the standard alphabet (A–Z, a–z, 0–9, +, /) with optional = padding.

Return value

  • A string containing the decoded bytes (often readable ASCII text).

Throws

  • InvalidCharacterError when the input is not valid Base64.

Common patterns

  • atob("SGVsbG8=") — decode a literal Base64 string.
  • atob(dataUrl.split(",")[1]) — decode the payload from a data URL.
  • atob(btoa(text)) === text — round-trip test for ASCII strings.

⚡ Quick Reference

TopicDetail
Encodes withbtoa()
Decodes withatob()
Valid inputBase64 text only (no data: prefix)
Bad inputThrows InvalidCharacterError
Unicode emojiNot supported directly—use UTF-8 helpers
Node.jsUse Buffer.from(str, "base64") instead

📋 atob() vs btoa()

These two window methods are inverses for Latin-1 binary strings. Encode before sending or storing; decode when reading back.

Encode
btoa("Hi")

Text → Base64

Decode
atob("SGk=")

Base64 → text

Round trip
atob(btoa(x))

Gets x back (ASCII)

Data URL
.split(",")[1]

Strip prefix first

Examples Gallery

Open DevTools Console (F12) and paste each snippet, or use the Try-it links. Every example shows decoded text you can verify.

📚 Getting Started

Decode fixed Base64 strings and verify with btoa().

Example 1 — Decode a Base64 String

Turn the encoded text SGVsbG8gd29ybGQh back into readable words.

JavaScript
const encoded = "SGVsbG8gd29ybGQh";
const decoded = atob(encoded);

console.log(decoded);  // "Hello world!"
Try It Yourself

How It Works

SGVsbG8gd29ybGQh is the Base64 form of “Hello world!” atob() reverses that encoding in one step.

📈 Practical Patterns

Round trips, data URLs, token payloads, and error handling.

Example 2 — Encode with btoa(), Decode with atob()

Prove the two methods are opposites for simple ASCII text.

JavaScript
const message = "CodeToFun";
const encoded = btoa(message);
const decoded = atob(encoded);

console.log(encoded);   // "Q29kZVRvRnVu"
console.log(decoded);   // "CodeToFun"
console.log(decoded === message);  // true
Try It Yourself

How It Works

btoa() produces Base64 from a binary string; atob() restores the original bytes. This round trip works reliably for ASCII characters in the Latin-1 range.

Example 3 — Decode Base64 from a Data URL

Data URLs include a MIME prefix. Split on the comma and decode only the Base64 part.

JavaScript
const dataUrl = "data:text/plain;base64,SGVsbG8=";
const base64Part = dataUrl.split(",")[1];
const text = atob(base64Part);

console.log(text);  // "Hello"
Try It Yourself

How It Works

Passing the entire data:text/plain;base64,... string to atob() throws an error because the prefix is not valid Base64. Always extract the payload after the comma.

Example 4 — Read a JWT Payload Segment

JSON Web Tokens have three dot-separated parts. Decode the middle (payload) segment only—not the whole token.

JavaScript
const token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiSm9obiJ9.signature";
const payloadBase64 = token.split(".")[1];
const payloadJson = atob(payloadBase64);

console.log(payloadJson);  // '{"name":"John"}'
Try It Yourself

How It Works

The header and signature segments use Base64URL encoding and may need character substitution (-+, _/) plus padding before atob(). This demo uses a payload that decodes directly for clarity—never treat decoded JWT data as trusted without verifying the signature on a server.

Example 5 — Safe Decode with try/catch

Catch invalid input instead of letting the script crash.

JavaScript
function safeAtob(input) {
  try {
    return atob(input);
  } catch (error) {
    console.error("Invalid Base64:", error.message);
    return null;
  }
}

console.log(safeAtob("SGVsbG8="));     // "Hello"
console.log(safeAtob("not!!!valid"));  // null (+ error logged)
Try It Yourself

How It Works

User-supplied or API data may contain corrupted Base64. A wrapper function logs the problem and returns null so the rest of your app can show a friendly message.

🚀 Common Use Cases

  • Data URLs — extract and decode embedded text or small assets from data: strings.
  • JWT inspection — read the payload segment for debugging (verify signatures server-side).
  • API responses — decode Base64 fields returned by legacy endpoints.
  • Learning exercises — pair with btoa() to understand encoding.
  • Cookie values — some apps store Base64-encoded metadata in cookies.
  • Unit tests — round-trip encoded fixtures in browser test runners.

🧠 How atob() Decodes Base64

1

Validate input

The engine checks that characters match the Base64 alphabet and padding rules.

Check
2

Map 4 → 3

Each group of four Base64 characters becomes three raw bytes.

Convert
3

Build string

Bytes are exposed as a JavaScript string (one char per byte).

Output
4

Readable text

For ASCII payloads encoded with btoa(), the result looks like ordinary text.

📝 Notes

  • atob() is a browser API on window; Node.js uses Buffer.from(s, "base64") instead.
  • Do not decode untrusted JWT payloads and treat them as verified identity—anyone can forge the middle segment.
  • Base64 increases size by roughly 33%—it is for transport, not compression or encryption.
  • Whitespace in input causes errors; trim strings if your source may include line breaks.
  • For binary files (images, PDFs), convert the binary string to a Uint8Array before further processing.
  • Modern alternative: Uint8Array.fromBase64() where supported for byte-oriented decoding.

Browser Support

Window.atob() has been available in browsers for many years and is part of the HTML Living Standard. It works in every current desktop and mobile browser.

Universal · Legacy API

Window.atob()

Supported in Chrome, Firefox, Safari, Edge, Opera, and WebViews. Also paired with btoa() everywhere both exist.

100% Universal support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
atob() Universal

Bottom line: Safe to use in any browser JavaScript environment. For Unicode-heavy data or server-side code, prefer UTF-8 aware APIs instead of raw atob/btoa.

Conclusion

The atob() method is the browser’s built-in Base64 decoder. Use it on valid Base64 payloads, strip data URL prefixes first, and handle errors when input comes from users or external APIs.

Practice the five examples, then explore btoa() for encoding and modern byte APIs when you outgrow Latin-1 limits.

💡 Best Practices

✅ Do

  • Strip data: prefixes before calling atob()
  • Wrap decoding in try/catch for external input
  • Decode JWT payload segments, not the full token string
  • Pair with btoa() to test round trips in learning code
  • Use server-side verification for security-sensitive tokens

❌ Don’t

  • Pass entire data URLs or JWT strings directly to atob()
  • Assume Base64 equals encryption—it is encoding only
  • Trust decoded JWT JSON without signature checks
  • Expect emoji/UTF-8 to round-trip through btoa/atob alone
  • Use atob() in Node without Buffer or polyfills

Key Takeaways

Knowledge Unlocked

Five things to remember about atob()

Your foundation for Base64 decoding in browser JavaScript.

5
Core concepts
🔄 02

Inverse

Pair with btoa().

Encode
🔗 03

Data URLs

Split on comma.

Prefix
04

Throws

Invalid Base64.

Error
🔐 05

Not crypto

Encoding only.

Security

❓ Frequently Asked Questions

It decodes a Base64-encoded string into a binary string (one byte per character code 0–255). For ASCII text that was encoded with btoa(), the result is readable plain text.
btoa() encodes a binary string to Base64; atob() does the reverse. They are inverse operations for data that fits the Latin-1 byte model both APIs expect.
The input is not valid Base64—wrong characters, bad padding, or extra whitespace. Wrap calls in try/catch or validate input before decoding.
No. Strip the prefix first (everything before the comma), then pass only the Base64 payload: atob(dataUrl.split(',')[1]).
No. JWTs use dot-separated parts. Decode the middle payload segment only, and convert Base64URL (- and _) to standard Base64 (+ and /) with padding if needed.
Not directly for arbitrary Unicode. btoa/atob work on binary strings, not UTF-8. For Unicode, encode with TextEncoder and decode bytes manually, or use modern APIs like Buffer (Node) or base64 decoding libraries.
Did you know?

The name atob is short for “ASCII to binary,” and btoa is “binary to ASCII.” They were added early in browser history—long before fetch, but still handy for quick Base64 tasks in front-end code.

Continue to blur()

Learn how to remove focus from the browser window with the window.blur() method.

blur() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful