Base64 Encoding in JavaScript

JavaScript provides built-in functions for Base64 encoding and decoding in both browser and Node.js environments.

Browser (btoa/atob)

For basic ASCII strings, use the built-in btoa() and atob() functions:

Encode to Base64

const text = "Hello, World!";
const encoded = btoa(text);
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="

Decode from Base64

const encoded = "SGVsbG8sIFdvcmxkIQ==";
const decoded = atob(encoded);
console.log(decoded); // "Hello, World!"

Handling Unicode

The btoa() function only works with ASCII. For Unicode strings, encode to UTF-8 first:

Encode Unicode to Base64

function encodeBase64(str) {
  const bytes = new TextEncoder().encode(str);
  let binary = '';
  bytes.forEach(b => binary += String.fromCharCode(b));
  return btoa(binary);
}

console.log(encodeBase64("Hello")); // Works with emojis too!

Decode Base64 to Unicode

function decodeBase64(base64) {
  const binary = atob(base64);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) {
    bytes[i] = binary.charCodeAt(i);
  }
  return new TextDecoder().decode(bytes);
}

console.log(decodeBase64("SGVsbG8=")); // "Hello"

Node.js (Buffer)

In Node.js, use the Buffer class:

Encode to Base64

const text = "Hello, World!";
const encoded = Buffer.from(text).toString('base64');
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="

Decode from Base64

const encoded = "SGVsbG8sIFdvcmxkIQ==";
const decoded = Buffer.from(encoded, 'base64').toString('utf8');
console.log(decoded); // "Hello, World!"

URL-Safe Base64

For URLs, replace + with - and / with _:

function toUrlSafe(base64) {
  return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

function fromUrlSafe(base64url) {
  let base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
  while (base64.length % 4) base64 += '=';
  return base64;
}

File to Base64

Convert a file to Base64 using FileReader:

function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

// Usage with file input
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', async (e) => {
  const base64 = await fileToBase64(e.target.files[0]);
  console.log(base64);
});