JavaScript Window btoa() Method

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

What You’ll Learn

The btoa() method encodes a string into Base64. This tutorial covers syntax, five practical examples, pairing with atob(), building data URLs, Unicode pitfalls, and safe error handling.

01

Syntax

btoa(string)

02

Input

Binary / ASCII string

03

Output

Base64 text

04

Pair

Inverse of atob()

05

Data URLs

Prefix + encoded payload

06

Not crypto

Encoding only

Introduction

Base64 turns raw bytes into text that travels safely through JSON, URLs, and HTML attributes. In browser JavaScript, window.btoa() performs that encoding: you pass a string whose characters represent bytes, and you get back a Base64 string.

The name means “binary to ASCII.” It is the partner of atob(), which decodes Base64 back. Together they are among the most common window helpers for quick encoding tasks—though they are not a substitute for encryption or full UTF-8 support.

Understanding the btoa() Method

btoa() reads each character code in the input string (must be 0–255) and outputs a Base64 representation using A–Z, a–z, 0–9, +, /, and = padding.

For beginner ASCII messages like "Hello", the API is a one-liner. For emoji or multilingual text, characters above code point 255 cause InvalidCharacterError unless you convert to UTF-8 bytes first.

💡
Beginner Tip

Base64 makes data bigger and readable by anyone with atob(). Use it for transport formats (data URLs, Basic auth headers), not to hide secrets.

📝 Syntax

General form of Window.btoa():

JavaScript
window.btoa(stringToEncode);
// shorthand (same in browsers):
btoa(stringToEncode);

Parameters

  • stringToEncode — a binary string: each character’s code unit must be in the range 0–255 (Latin-1 bytes).

Return value

  • A Base64-encoded ASCII string.

Throws

  • InvalidCharacterError when a character is outside the Latin-1 byte range.

Common patterns

  • btoa("Hello") — encode plain ASCII text.
  • "data:text/plain;base64," + btoa("Hi") — build a text data URL.
  • "Basic " + btoa(username + ":" + password) — HTTP Basic auth header value (HTTPS only in production).

⚡ Quick Reference

TopicDetail
Encodes withbtoa()
Decodes withatob()
ASCII round tripatob(btoa(x)) === x
Unicode emojiOften throws—encode UTF-8 bytes first
SecurityNot encryption
Node.jsBuffer.from(s).toString("base64")

📋 btoa() vs atob()

Encode before sending or storing; decode when reading back. Direction is the only difference for ASCII data.

Encode
btoa("Hi")

Text → Base64

Decode
atob("SGk=")

Base64 → text

Round trip
atob(btoa(x))

Restore ASCII x

Data URL
data:...;base64,

Prefix + btoa()

Examples Gallery

Open DevTools Console (F12) or use the Try-it links. Each example shows the Base64 output you can verify with atob().

📚 Getting Started

Encode ASCII strings and verify with atob().

Example 1 — Encode a Simple String

Convert "Hello, World!" into Base64.

JavaScript
const text = "Hello, World!";
const encoded = btoa(text);

console.log(encoded);  // "SGVsbG8sIFdvcmxkIQ=="
Try It Yourself

How It Works

Each byte of the input string is grouped and mapped to Base64 characters. Padding == appears when the byte length is not a multiple of three.

📈 Practical Patterns

Round trips, data URLs, headers, and error handling.

Example 2 — Round Trip with atob()

Encode, decode, and confirm the original message returns unchanged.

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

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

How It Works

btoa() and atob() are inverses for ASCII strings. This test is a quick sanity check when debugging encoding pipelines.

Example 3 — Build a Text Data URL

Combine a MIME prefix with the Base64 payload from btoa().

JavaScript
const text = "Hello";
const dataUrl = "data:text/plain;base64," + btoa(text);

console.log(dataUrl);
// "data:text/plain;base64,SGVsbG8="
Try It Yourself

How It Works

Data URLs embed content inline. The Base64 part comes from btoa(); images from canvas use canvas.toDataURL(), which already includes Base64—no second btoa() needed.

Example 4 — HTTP Basic Authorization Header

Encode username:password for a Basic auth header (demo credentials only—always use HTTPS in production).

JavaScript
const username = "demoUser";
const password = "demoPass";
const credentials = username + ":" + password;
const headerValue = "Basic " + btoa(credentials);

console.log(headerValue);
// "Basic ZGVtb1VzZXI6ZGVtb1Bhc3M="
Try It Yourself

How It Works

The server decodes the Base64 blob back to username:password. Base64 is not encryption—anyone who intercepts the header can decode it, so HTTPS is mandatory.

Example 5 — Safe Encode with try/catch

Handle Unicode input that exceeds the Latin-1 range.

JavaScript
function safeBtoa(input) {
  try {
    return btoa(input);
  } catch (error) {
    console.error("Cannot encode:", error.message);
    return null;
  }
}

console.log(safeBtoa("Hello"));  // "SGVsbG8="
console.log(safeBtoa("Hello 😀"));  // null (+ error logged)
Try It Yourself

How It Works

Emoji and many Unicode characters exceed byte 255, so btoa() throws. Wrap calls that handle user input, or pre-encode UTF-8 bytes before calling btoa().

🚀 Common Use Cases

  • Data URLs — embed small text or binary snippets in HTML/CSS.
  • Basic authentication — build Authorization header values (with HTTPS).
  • API payloads — encode binary-safe fields in JSON when required by legacy APIs.
  • Debugging — compare encoded output with server-side Base64 tools.
  • Learning — pair with atob() to understand encoding pipelines.
  • Tests — generate predictable Base64 fixtures in browser test runners.

🧠 How btoa() Encodes Base64

1

Read bytes

Each input character code must be 0–255 or encoding aborts.

Validate
2

Group bits

Bytes are grouped in threes and mapped to four Base64 symbols.

Convert
3

Add padding

= characters pad the output when byte count is not divisible by three.

Pad
4

Return string

A Base64 ASCII string ready for URLs, headers, or storage.

📝 Notes

  • Base64 output is roughly 33% larger than the original binary data.
  • canvas.toDataURL() already returns Base64—do not wrap that payload in btoa() again.
  • JWT segments use Base64URL, which may need character swaps before btoa/atob workflows.
  • For UTF-8 text, convert bytes first: TextEncoder → binary string → btoa().
  • Never store passwords with Base64 alone—it is trivially reversible.
  • Node.js prefers Buffer.from(string, "utf8").toString("base64") for server code.

Browser Support

Window.btoa() is part of the HTML Living Standard and has been available in browsers for many years alongside atob().

Universal · Legacy API

Window.btoa()

Supported in Chrome, Firefox, Safari, Edge, Opera, and WebViews. Behavior matches atob() availability across platforms.

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
btoa() Universal

Bottom line: Safe to use in any browser JavaScript environment for ASCII/Latin-1 data. Plan UTF-8 helpers separately for international text.

Conclusion

The btoa() method is the browser’s built-in Base64 encoder. Use it for ASCII strings, data URL payloads, and Basic auth headers—always remembering that encoding is not encryption.

Pair it with atob() for round trips, wrap user input in try/catch, and reach for UTF-8 aware tools when emoji or multilingual text enters the picture.

💡 Best Practices

✅ Do

  • Use btoa() for ASCII and Latin-1 byte strings
  • Verify with atob(btoa(x)) === x while learning
  • Wrap encoding in try/catch for user input
  • Send Basic auth only over HTTPS
  • Use canvas.toDataURL() for image Base64 directly

❌ Don’t

  • Treat Base64 as password protection
  • Pass emoji directly to btoa() without UTF-8 prep
  • Double-encode data that is already Base64
  • Validate input with a binary-digit regex—btoa expects byte strings
  • Assume btoa() exists unchanged in all Node versions

Key Takeaways

Knowledge Unlocked

Five things to remember about btoa()

Your foundation for Base64 encoding in browser JavaScript.

5
Core concepts
🔄 02

Inverse

Pair with atob().

Decode
🔐 03

Not secret

Encoding only.

Security
04

Unicode

May throw.

Limit
🔗 05

Data URLs

Prefix + payload.

Pattern

❓ Frequently Asked Questions

It encodes a binary string into Base64 text. Each character in the input represents one byte (0–255). For plain ASCII text, the result is a portable Base64 string you can store or transmit.
btoa() encodes to Base64; atob() decodes back. They are inverse operations: atob(btoa(text)) returns the original string for ASCII input.
The input string contains a character outside the Latin-1 byte range (code point above 255), such as many emoji or some Unicode letters. btoa() cannot encode those directly.
No. Base64 is encoding, not encryption. Anyone can decode with atob(). Never rely on btoa() alone to hide passwords or secrets.
Convert UTF-8 bytes first—for example, encode with TextEncoder, build a binary string from bytes, then call btoa(). Or use modern helpers like Uint8Array.toBase64() where available.
Not on window by default. In Node use Buffer.from(str, 'utf8').toString('base64') or the global btoa in newer Node versions.
Did you know?

The names btoa and atob date back to Netscape’s early browsers. Modern code often uses Buffer, TextEncoder, or Uint8Array.toBase64(), but btoa() remains the quickest way to encode ASCII in a script tag or DevTools snippet.

Continue to clearInterval()

Learn how to stop a repeating timer started with setInterval().

clearInterval() 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