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
Fundamentals
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.
Concept
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.
Foundation
📝 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).
Cheat Sheet
⚡ Quick Reference
Topic
Detail
Encodes with
btoa()
Decodes with
atob()
ASCII round trip
atob(btoa(x)) === x
Unicode emoji
Often throws—encode UTF-8 bytes first
Security
Not encryption
Node.js
Buffer.from(s).toString("base64")
Compare
📋 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()
Hands-On
Examples Gallery
Open DevTools Console (F12) or use the Try-it links. Each example shows the Base64 output you can verify with atob().
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).
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.
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().
Applications
🚀 Common Use Cases
Data URLs — embed small text or binary snippets in HTML/CSS.
Never store passwords with Base64 alone—it is trivially reversible.
Node.js prefers Buffer.from(string, "utf8").toString("base64") for server code.
Compatibility
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 ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll 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.
Wrap Up
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.
Validate input with a binary-digit regex—btoa expects byte strings
Assume btoa() exists unchanged in all Node versions
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about btoa()
Your foundation for Base64 encoding in browser JavaScript.
5
Core concepts
📝01
Syntax
btoa(string)
API
🔄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.