Encoding Strings to Base64: The Complete Guide
Converting a string to Base64 is one of the most common encoding operations in modern web development. You need it when embedding text-based secrets in URLs, sending structured data across text-only transports, storing binary-looking blobs in config files, or building your own JWT-style tokens. This guide covers everything: the concept, worked examples in every major language, the UTF-8 pitfall, and when NOT to use Base64.
The UTF-8 Pitfall Every Developer Hits
Every JavaScript developer who tries to Base64-encode a Chinese character or emoji using the built-in btoa() function gets this error:
btoa('Hello 世界');
// Uncaught InvalidCharacterError: Failed to execute 'btoa' on 'Window':
// The string to be encoded contains characters outside of the Latin1 range.The reason: btoa() was designed in 1995 for Latin-1 (single-byte) text. Any character with a code point above 255 breaks it. The fix — used by every modern encoder including the PromptSpace tool above — is to first convert the string to UTF-8 bytes, then Base64-encode those bytes:
function stringToBase64(str) {
const utf8Bytes = new TextEncoder().encode(str); // string → Uint8Array
const binString = String.fromCharCode(...utf8Bytes); // bytes → binary string
return btoa(binString); // binary string → Base64
}
stringToBase64('Hello 世界'); // "SGVsbG8g5LiW55WM"
stringToBase64('👋 Hi'); // "8J+RiyBIaQ=="String-to-Base64 in Every Major Language
Python
import base64
# Python strings are Unicode by default — encode to bytes first
text = 'Hello 世界'
encoded = base64.b64encode(text.encode('utf-8')).decode('ascii')
print(encoded) # "SGVsbG8g5LiW55WM"
# Decode back
decoded = base64.b64decode(encoded).decode('utf-8')
print(decoded) # "Hello 世界"Go
import (
"encoding/base64"
"fmt"
)
func main() {
text := "Hello 世界"
encoded := base64.StdEncoding.EncodeToString([]byte(text))
fmt.Println(encoded) // "SGVsbG8g5LiW55WM"
}Rust
use base64::{Engine as _, engine::general_purpose::STANDARD};
fn main() {
let text = "Hello 世界";
let encoded = STANDARD.encode(text.as_bytes());
println!("{}", encoded); // "SGVsbG8g5LiW55WM"
}Java
import java.util.Base64;
import java.nio.charset.StandardCharsets;
String text = "Hello 世界";
String encoded = Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8));
System.out.println(encoded); // "SGVsbG8g5LiW55WM"PHP
$text = 'Hello 世界';
$encoded = base64_encode($text); // PHP handles UTF-8 natively
echo $encoded; // "SGVsbG8g5LiW55WM"When to Encode a String to Base64
- URL parameters — pack a JSON blob into a single query string param
- Cookies — store structured data in a cookie value without picking a delimiter
- Environment variables — inject multi-line secrets (PEM keys, JSON) into a single env var
- HTTP Basic Auth — the
user:passstring is Base64-encoded in the Authorization header - JWT payloads — the JSON header and payload are Base64URL-encoded segments of a JWT
- Data URLs — embed a text blob (SVG, HTML, CSS) directly in an HTML attribute
- Config files — put binary-looking content into a YAML/TOML file that only accepts strings
When NOT to Encode a String to Base64
Base64 is NOT compression, NOT encryption, and NOT authentication. Never use it for:
- Hiding passwords or API keys — decoders are one line of code in every language
- Reducing size — Base64 makes strings 33% larger, not smaller
- Detecting tampering — anyone can decode, modify, and re-encode
- Storing plain text — if a plain string works, use it; Base64 adds noise for no reason
Key Facts
- Input:
- Any string — ASCII, UTF-8, Unicode, multi-line, JSON
- Output size:
- Approximately 4/3 the UTF-8 byte length of the input
- Character encoding:
- UTF-8 (safe for all Unicode)
- Reversible:
- Yes — lossless round-trip
- Runs where:
- Fully in your browser — no upload
Related Base64 Tools
- Base64 Encode Online — general-purpose encoder with URL-safe option
- Text to Base64 Converter — plain-text focused conversion guide
- Base64 Encode in JavaScript — deep dive on btoa, TextEncoder, and Buffer
- Base64 Encode in Python — b64encode with UTF-8 examples
- Base64 Decode — decode a Base64 string back to text
- URL Encoder — percent-encode strings for URLs