encodeBase64
Encodes a string to Base64 format.
1/**
2 * Encodes a string to Base64 format.
3 *
4 * @param str - The input string to encode.
5 * @returns A Base64-encoded string.
6 */
7export function encodeBase64(str: string): string {
8 if (typeof window !== 'undefined' && typeof btoa === 'function') {
9 return btoa(unescape(encodeURIComponent(str)));
10 }
11
12 return Buffer.from(str, 'utf-8').toString('base64');
13}
Dual Environment Support
Works seamlessly in both browser and Node.js environments by detecting
btoa
or falling back toBuffer
.Unicode-Safe Encoding
Uses
encodeURIComponent
andunescape
to properly handle multi-byte characters before Base64 encoding.Minimal Dependencies
Relies only on built-in APIs (
btoa
,Buffer
) without introducing external libraries.Consistent Output
Guarantees a stable Base64 string regardless of environment differences in character encoding.
Tests | Examples
1test('encodeBase64 - encodes plain ASCII text', () => {
2 expect(encodeBase64('Hello')).toBe('SGVsbG8=');
3});
4
5test('encodeBase64 - encodes empty string', () => {
6 expect(encodeBase64('')).toBe('');
7});
8
9test('encodeBase64 - encodes Unicode characters', () => {
10 expect(encodeBase64('Привет')).toBe('0J/RgNC40LLQtdGC');
11});
12
13test('encodeBase64 - encodes emojis', () => {
14 expect(encodeBase64('💡🔥')).toBe('8J+SqfCfkbE=');
15});
Common Use Cases
Data Serialization
Encode text or binary data for safe transport in URLs, HTTP headers, or JSON payloads.
Authentication Tokens
Prepare strings for use in Basic Auth headers or other token formats.
Embedding Binary in Text
Encode images, fonts, or files as Base64 for inline use in HTML/CSS.
Secure Local Storage
Store stringified and encoded sensitive information (e.g. settings) in localStorage or cookies.