How to Encode Base64 in JavaScript

JavaScript provides built-in mechanisms for Base64 encoding and decoding, but understanding the quirks of these APIs is essential for writing robust code. In this guide, we'll cover how to encode strings and binary data in both browser (frontend) and Node.js (backend) environments.

Frontend: The Browser Environment

The browser provides two global functions for Base64:

The Legacy Approach (For basic English text)

If you are absolutely certain your text contains only standard 8-bit ASCII characters (e.g., standard English letters and numbers without accents), you can use btoa() directly.

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

The Modern, Safe Approach (For Unicode and Emojis)

As covered in our UTF-8 guide, calling btoa("🔥") will instantly crash your application. To safely encode any user-generated content, you must use the TextEncoder API to convert the string to a byte array first.

function encodeUtf8ToBase64(str) {
    const bytes = new TextEncoder().encode(str);
    const binary = String.fromCodePoint(...bytes);
    return btoa(binary);
}

console.log(encodeUtf8ToBase64("Hello 🔥")); // SGVsbG8g8J+UpQ==

Encoding Files in the Browser

Often, you don't want to encode a text string; you want to encode a file (like an image) that the user uploaded. To do this, you use the FileReader API to read the file as a Data URL, which automatically encodes the file's binary contents into Base64.

const fileInput = document.querySelector('input[type="file"]');

fileInput.addEventListener('change', (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();

    reader.onload = (e) => {
        // e.target.result contains the Base64 Data URL
        console.log(e.target.result); 
    };

    // This triggers the Base64 encoding process
    reader.readAsDataURL(file);
});

Backend: The Node.js Environment

Node.js does not use btoa(). Instead, it relies on the highly optimized Buffer object. Buffers are designed to handle raw binary data.

Encoding Strings in Node.js

To encode a string in Node.js, you instantiate a Buffer with your string and its encoding type (usually utf-8), and then convert that Buffer to a base64 string.

const text = "Hello from the server! 🚀";
// Create a buffer from the UTF-8 string
const buffer = Buffer.from(text, 'utf-8');
// Convert the buffer to a Base64 string
const base64String = buffer.toString('base64');

console.log(base64String);

Encoding Files in Node.js

If you need to read a file from the filesystem and encode it to Base64 (for example, to attach it to a JSON API response), you use the fs (File System) module.

const fs = require('fs');

// Read the file directly into a binary Buffer
const fileBuffer = fs.readFileSync('./image.png');

// Convert the binary buffer to a Base64 string
const base64Image = fileBuffer.toString('base64');

// Optional: Format it as a Data URL for HTML/CSS insertion
const dataUrl = `data:image/png;base64,${base64Image}`;

Summary

Base64 encoding in JavaScript depends entirely on the environment. In the browser, stick to TextEncoder paired with btoa() for strings, and FileReader for files. In Node.js, rely exclusively on the Buffer API. If you need a quick, reliable conversion without writing code, use our free Online Base64 Encoder.