How to Do Base64 Encoding in JavaScript

Published on 2026-02-06

How to Do Base64 Encoding in JavaScript

How to Do Base64 Encoding in JavaScript

Base64 encoding is an essential technique in web development. Whether you need to pass an authentication token, embed an image directly into CSS or HTML to save network requests, or serialize data for JSON, Base64 is the go-to solution.

In this comprehensive tutorial, we will cover how to perform Base64 encoding in JavaScript. Because JavaScript runs in two very different environments—the web browser and Node.js—we will cover the specific methods for both. Most importantly, we will answer the highly requested question: how to convert an image to base64 in javascript.

Key Takeaways

1. Base64 Encoding Strings in the Browser

Web browsers provide two natively supported, global functions for Base64 manipulation: - btoa(): (Binary to ASCII) Encodes a string to Base64. - atob(): (ASCII to Binary) Decodes a Base64 string.

Encoding and Decoding Example

// The string we want to encode
const originalText = "Hello, JavaScript!";

// Encode it
const encodedText = btoa(originalText);
console.log("Encoded:", encodedText); // Output: SGVsbG8sIEphdmFTY3JpcHQh

// Decode it back
const decodedText = atob(encodedText);
console.log("Decoded:", decodedText); // Output: Hello, JavaScript!

The Unicode (UTF-8) Problem

A major gotcha with btoa() is that it only supports ASCII characters. If you try to encode emojis or characters with accents (e.g., btoa("🚀")), JavaScript will throw an InvalidCharacterError.

To safely encode Unicode strings, you must first encode the string as UTF-8 bytes using encodeURIComponent or the modern TextEncoder API.

Unicode Safe Encoding:

const unicodeText = "Hello 🌍!";
const utf8Bytes = new TextEncoder().encode(unicodeText);
const base64String = btoa(String.fromCharCode(...utf8Bytes));

console.log(base64String); // Works perfectly!

2. Base64 Encoding Strings in Node.js

Node.js is designed for server-side operations and handles binary data via the Buffer class. While newer versions of Node.js (>v16) have added global support for btoa(), the standard, most robust way to handle Base64 in Node is using Buffers.

Encoding in Node.js

const originalText = "Hello, Node.js!";

// Create a buffer from the string, then convert it to a base64 string
const encodedText = Buffer.from(originalText, 'utf8').toString('base64');

console.log("Encoded:", encodedText); // Output: SGVsbG8sIE5vZGUuanMh

Decoding in Node.js

const encodedText = "SGVsbG8sIE5vZGUuanMh";

// Create a buffer from the base64 string, then convert to utf8 text
const decodedText = Buffer.from(encodedText, 'base64').toString('utf8');

console.log("Decoded:", decodedText); // Output: Hello, Node.js!

3. How to Convert an Image to Base64 in JavaScript (Browser)

One of the most practical applications of Base64 is dealing with file uploads or dynamically rendering images. If a user selects an image via an <input type="file">, you can convert that file to a Base64 Data URL so it can be previewed immediately without uploading it to a server.

Here is exactly how to convert an image to base64 in javascript using the FileReader API.

The HTML

<input type="file" id="imageInput" accept="image/*">
<img id="imagePreview" alt="Image preview will appear here" />

The JavaScript

const fileInput = document.getElementById('imageInput');
const imagePreview = document.getElementById('imagePreview');

fileInput.addEventListener('change', function(event) {
    const file = event.target.files[0];

    if (file) {
        const reader = new FileReader();

        // This event fires when the file has been successfully read
        reader.onload = function(e) {
            // The result is a Base64 encoded Data URL
            const base64Image = e.target.result;

            console.log("Base64 Output:", base64Image);

            // Set the src of the image tag to preview the image
            imagePreview.src = base64Image;
        };

        // Read the file as a Data URL (which uses Base64 encoding)
        reader.readAsDataURL(file);
    }
});

When you use readAsDataURL(), the output will look something like this: data:image/jpeg;base64,/9j/4AAQSkZJ.... This entire string can be passed directly into the src attribute of an <img> tag or used in a CSS background-image property.

Conclusion

JavaScript provides versatile ways to handle Base64 encoding depending on your environment. Whether you are using btoa() in the browser, manipulating Buffer objects in Node.js, or leveraging FileReader to understand how to convert an image to base64 in javascript, these techniques are foundational for modern web development. Just remember to handle Unicode carefully when working in the browser!

FAQs

Q: Should I store large images as Base64 strings in my database? A: Generally, no. Base64 encoding increases the file size by about 33%. Storing large Base64 strings in a database can bloat your storage and slow down query times. It is better to store images in a cloud storage bucket (like AWS S3) and save the URL in your database.

Q: Why does btoa() fail when I try to encode an Emoji? A: btoa() expects a 1-byte binary string (ASCII). Emojis are multi-byte Unicode characters. You must convert the Unicode string to UTF-8 bytes before passing it to btoa().

Q: Can I use atob() and btoa() in Node.js? A: Yes, in Node.js version 16.0.0 and later, atob and btoa are available as global functions. However, using Buffer is still the industry standard for backend JavaScript.

Prosun

About the Author: Prosun

Prosun is a passionate web developer and technical writer specializing in data encoding, cybersecurity, and modern web architectures. As the creator of GoBase64, he is dedicated to building fast, privacy-focused tools for the developer community. He also manages tinyfont.me and htmlcode.blog.

From the GoBase64 Blog