
How to Encode and Decode Base64 in JavaScript
The need to encode Base64 in JavaScript comes up constantly — embedding images in HTML, transmitting binary data over JSON APIs, handling JWTs, or storing binary blobs in text-based formats. JavaScript gives you several ways to do this depending on your environment (browser vs. Node.js) and data type (text vs. binary). This guide covers every method, explains the Unicode pitfall that trips up most developers, and shows when to use Base64URL over standard Base64. Browser: btoa() and atob() All modern browsers provide the built-in btoa() (binary to ASCII) and atob() (ASCII to binary) functions: // Encode a string to Base64 const encoded = btoa ( ' Hello, World! ' ); console . log ( encoded ); // "SGVsbG8sIFdvcmxkIQ==" // Decode Base64 back to string const decoded = atob ( ' SGVsbG8sIFdvcmxkIQ== ' ); console . log ( decoded ); // "Hello, World!" Simple enough — but there is a critical catch. The Unicode Pitfall btoa() only handles strings where every character has a code point of 255 or l
Continue reading on Dev.to Tutorial
Opens in a new tab




