Base64 Encoding Explained: Complete Developer Guide 2026

Base64 encoding is one of those technologies that's everywhere in software development β€” from data URIs in HTML to email attachments, from JWT tokens to API authentication. But how does it actually work? And when should (and shouldn't) you use it? This guide covers everything.

Encode/Decode Base64 Free

Instant Base64 encoding and decoding in your browser. No server calls.

Try Base64 Tool

What is Base64 Encoding?

Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format. It uses 64 printable characters (A-Z, a-z, 0-9, +, /) to represent any binary data.

πŸ’‘ Why "Base64"?

The name comes from using 6 bits (2^6 = 64) to represent each character. Since each Base64 character encodes 6 bits, every 3 bytes (24 bits) of binary data becomes 4 Base64 characters.

The Base64 Character Set

Base64 uses exactly 64 characters:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
0 1 2 3 4 5 6 7 8 9
+ /

Each character maps to a value from 0 to 63:

Value Range Characters Example
0-25 A-Z A=0, B=1, ..., Z=25
26-51 a-z a=26, b=27, ..., z=51
52-61 0-9 0=52, 1=53, ..., 9=61
62 + Plus sign
63 / Forward slash

How Base64 Encoding Works

Let's walk through encoding "Hi" step by step:

Step 1: Convert to Binary

'H' = 72 (ASCII) = 01001000
'i' = 105 (ASCII) = 01101001

Binary: 01001000 01101001

Step 2: Group into 6-bit Chunks

01001000 01101001
010010 000110 100100 (pad with zeros)

6-bit values: 18, 6, 36

Step 3: Map to Base64 Characters

18 β†’ S
6  β†’ G
36 β†’ k

Result: SGk= (padding added)

Understanding Padding

Base64 requires the output length to be a multiple of 4. If the input isn't divisible by 3, padding characters (=) are added:

  • 1 byte input β†’ 2 Base64 chars + ==
  • 2 bytes input β†’ 3 Base64 chars + =
  • 3+ bytes input β†’ No padding needed (if divisible by 3)

πŸ’‘ Size Overhead

Base64 encoding increases data size by approximately 33%. Every 3 bytes become 4 Base64 characters.

Base64 in JavaScript

JavaScript provides built-in methods for Base64 encoding:

Basic Encoding/Decoding

// Encode to Base64
const text = 'Hello, DevKits!';
const encoded = btoa(text);
console.log(encoded); // "SGVsbG8sIERldktpdHMh"

// Decode from Base64
const decoded = atob(encoded);
console.log(decoded); // "Hello, DevKits!"

Handling Unicode (UTF-8)

The built-in btoa() doesn't handle Unicode properly. For UTF-8 strings:

// Encode UTF-8 to Base64
function utf8ToBase64(str) {
  return btoa(unescape(encodeURIComponent(str)));
}

// Decode Base64 to UTF-8
function base64ToUtf8(base64) {
  return decodeURIComponent(escape(atob(base64)));
}

// Example with emoji
const text = 'Hello δΈ–η•Œ 🌍';
const encoded = utf8ToBase64(text);
console.log(encoded); // "SGVsbG8g5LiW55WMIPCfjI0="

const decoded = base64ToUtf8(encoded);
console.log(decoded); // "Hello δΈ–η•Œ 🌍"

Base64 for Binary Data

// Convert ArrayBuffer to Base64
function arrayBufferToBase64(buffer) {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary);
}

// Convert Base64 to ArrayBuffer
function base64ToArrayBuffer(base64) {
  const binaryString = atob(base64);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes.buffer;
}

URL-Safe Base64

Standard Base64 uses + and /, which have special meanings in URLs. URL-safe Base64 replaces these:

  • + β†’ - (hyphen)
  • / β†’ _ (underscore)
// Standard Base64 to URL-safe
function base64ToUrlSafe(base64) {
  return base64
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, ''); // Padding often omitted in URLs
}

// URL-safe to Standard Base64
function urlSafeToBase64(urlSafe) {
  // Add padding if needed
  let padded = urlSafe;
  while (padded.length % 4 !== 0) {
    padded += '=';
  }
  return padded
    .replace(/-/g, '+')
    .replace(/_/g, '/');
}

// Example
const standard = 'SGVsbG8+V29ybGQ/';
const urlSafe = base64ToUrlSafe(standard);
console.log(urlSafe); // "SGVsbG8-V29ybGQ"

⚠️ Common Pitfall

JWT tokens use URL-safe Base64 without padding. Don't try to decode JWT parts with standard Base64 decoders without converting first!

Common Use Cases

1. Data URIs in HTML

<!-- Embed image directly in HTML -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...">

<!-- Embed SVG -->
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0i...">

2. Basic Authentication

// HTTP Basic Auth header
const credentials = 'username:password';
const encoded = btoa(credentials);
console.log(encoded); // "dXNlcm5hbWU6cGFzc3dvcmQ="

// Authorization header
const authHeader = `Basic ${encoded}`;
// "Basic dXNlcm5hbWU6cGFzc3dvcmQ="

3. JWT Tokens

// JWT structure (header.payload.signature)
const jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U';

// Each part is URL-safe Base64 encoded JSON
const [headerB64, payloadB64, signature] = jwt.split('.');
const header = JSON.parse(atob(urlSafeToBase64(headerB64)));

4. File Uploads

// Convert file to Base64 for API upload
function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

// Usage
const fileInput = document.querySelector('input[type="file"]');
const base64Data = await fileToBase64(fileInput.files[0]);
// Send to API
await fetch('/api/upload', {
  method: 'POST',
  body: JSON.stringify({ file: base64Data })
});

5. Email Attachments (MIME)

Email protocols (SMTP, MIME) use Base64 to encode binary attachments so they can be transmitted as text.

Security Considerations

⚠️ Base64 is NOT Encryption

Base64 encoding provides zero security. Anyone can decode Base64 without a key. Never use it to "hide" sensitive data.

What Base64 Is:

  • βœ… An encoding scheme (binary β†’ text representation)
  • βœ… Reversible without any key
  • βœ… Designed for compatibility, not security

What Base64 Is NOT:

  • ❌ Encryption (no secret key)
  • ❌ Hashing (reversible)
  • ❌ Obfuscation (trivially decoded)
  • ❌ Compression (actually expands data)

Secure Alternatives

Use Case Base64 Secure Alternative
Hide passwords ❌ btoa(password) βœ… bcrypt/Argon2 hash
Encrypt data ❌ Base64 βœ… AES-256 encryption
Sign tokens ❌ Base64 signature βœ… HMAC/HMAC-SHA256
Hash data ❌ Base64 hash βœ… SHA-256/SHA-3

Base64 in APIs

Many APIs use Base64 for data transmission:

GitHub API

// Get file contents
const response = await fetch('https://api.github.com/repos/owner/repo/contents/file.txt');
const data = await response.json();

// File content is Base64 encoded
const content = atob(data.content);
console.log(content);

Cloud Storage

// Upload to cloud storage
const fileData = await readFileAsBase64(file);

await fetch('https://storage.api.com/upload', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    filename: file.name,
    content: fileData, // Base64 string
    encoding: 'base64'
  })
});

Encode/Decode Base64 Instantly

Our Base64 tool handles UTF-8, URL-safe encoding, and batch operations. All in your browser.

Try Base64 Encoder

Performance Considerations

For large files, Base64 encoding can be a bottleneck:

Browser Performance

// Slow: Encoding large files synchronously
const largeBase64 = btoa(largeString); // Blocks main thread

// Better: Use Web Workers for large files
const worker = new Worker('base64-worker.js');
worker.postMessage({ data: largeBuffer, action: 'encode' });
worker.onmessage = (e) => console.log('Encoded:', e.data);

Node.js Performance

// Fast: Use Buffer API
const encoded = Buffer.from(binaryData).toString('base64');
const decoded = Buffer.from(encoded, 'base64').toString('binary');

// For streams (large files)
const fs = require('fs');
const base64Stream = fs.createReadStream('large-file.bin')
  .pipe(new Base64Encoder())
  .pipe(fs.createWriteStream('large-file.b64'));

Base64 Tools & Libraries

  • DevKits Base64 Tool β€” Free online encoder/decoder
  • atob()/btoa() β€” Browser built-in
  • Buffer β€” Node.js native
  • base64-js β€” npm package for custom implementations
  • js-base64 β€” UTF-8 safe Base64 library

Conclusion

Base64 encoding is a fundamental technology in web development, enabling binary data to be safely transmitted over text-based protocols. Whether you're working with data URIs, JWT tokens, API authentication, or file uploads, understanding Base64 is essential.

Remember the key points:

  • Base64 is encoding, NOT encryption β€” don't use it for security
  • Expect ~33% size increase
  • Use URL-safe Base64 for tokens and URLs
  • Handle UTF-8 properly when encoding non-ASCII text

Try DevKits Base64 Tool

Free, fast, and 100% client-side Base64 encoding/decoding.

Encode/Decode Base64

Related Reading: