btoa-safe
Safely encodes a string to base64. Handles Unicode properly using TextEncoder.
1/**
2 * Safely encodes a string to base64.
3 * Handles Unicode properly using TextEncoder.
4 *
5 * @param str - The input string.
6 * @returns Base64-encoded string or null if encoding fails.
7 */
8export function btoaSafe(str: string): string | null {
9 try {
10 const encoded = new TextEncoder().encode(str);
11 const binary = String.fromCharCode(...encoded);
12 return btoa(binary);
13 } catch {
14 return null;
15 }
16}
Unicode-Safe Encoding
Uses
TextEncoder
to properly handle multibyte Unicode characters, avoiding malformed output compared to naivebtoa
.Graceful Failure Handling
Returns
null
instead of throwing, making it safer to use in unpredictable environments or with untrusted input.Compact and Efficient
Lightweight implementation using native browser APIs without external dependencies.
Cross-Browser Compatibility
Works in modern browsers that support
TextEncoder
, which is widely available across platforms.
Tests | Examples
1test('btoaSafe - encodes ASCII string', () => {
2 expect(btoaSafe('Hello')).toBe('SGVsbG8=');
3});
4
5test('btoaSafe - encodes Unicode string', () => {
6 expect(btoaSafe('Привет')).toBe('0J/RgNC40LLQtdGC');
7});
8
9test('btoaSafe - encodes string with emojis', () => {
10 expect(btoaSafe('🔥🚀')).toBe('8J+SqfCfkb0=');
11});
12
13test('btoaSafe - empty string', () => {
14 expect(btoaSafe('')).toBe('');
15});
16
17test('btoaSafe - handles malformed input gracefully', () => {
18 expect(btoaSafe((undefined as any))).toBeNull();
19});
Common Use Cases
Encoding Data for URL or API Transmission
Convert user input or payloads into base64 for transmission over query parameters or headers.
Client-Side File/Data Processing
Safely encode text content (e.g., logs, form data) before saving or exporting.
Local Storage or Cookie Storage
Store encoded Unicode strings in
localStorage
,sessionStorage
, or cookies.Basic Auth Header Creation
Encode credentials or tokens in a base64-compatible format for use in
Authorization
headers.Generating Data URLs
Prepare encoded strings to embed inline content (e.g., images, text files) via
data:
URIs.