Encodes bytes to standard base64 string using RFC 4648 alphabet (A-Z, a-z, 0-9, +, /) with padding.
const data = new Uint8Array([72, 101, 108, 108, 111])const encoded = Base64.encode(data)// "SGVsbG8="// Works with any binary dataconst binary = new Uint8Array([0xff, 0xfe, 0xfd])const encoded2 = Base64.encode(binary)// "/v79"
Parameters:
data: Uint8Array - Binary data to encode
Returns:Base64String - Standard base64-encoded string with paddingExample:
Encodes bytes to URL-safe base64 string. Uses URL-safe alphabet (A-Z, a-z, 0-9, -, _) and removes padding characters.Differences from standard base64:
Replaces + with -
Replaces / with _
Removes = padding
const data = new Uint8Array([255, 254, 253])const encoded = Base64.encodeUrlSafe(data)// URL-safe, no padding// Safe for URLsconst url = `https://example.com/data/${encoded}`// Safe for filenamesconst filename = `cache-${encoded}.dat`
Parameters:
data: Uint8Array - Binary data to encode
Returns:Base64UrlString - URL-safe base64 string without paddingExample:
// Encode token for URLconst tokenBytes = Bytes16() // 16-byte random tokencrypto.getRandomValues(tokenBytes)const token = Base64.encodeUrlSafe(tokenBytes)// Use in URL without encodingconst apiUrl = `https://api.example.com/auth?token=${token}`
Encodes UTF-8 string to URL-safe base64. Combines TextEncoder with URL-safe base64 encoding.
const email = "user@example.com"const encoded = Base64.encodeStringUrlSafe(email)// No +, /, or = characters - safe for URLs// Use in URL path or query parameterconst url = `/users/${encoded}`
// Use standard for general data encodingconst serialized = Base64.encodeString(JSON.stringify(data))// Use URL-safe when output appears in URLsconst urlSafeId = Base64.encodeUrlSafe(idBytes)const link = `https://example.com/item/${urlSafeId}` // No escaping needed// Use URL-safe for filenamesconst filename = `cache-${Base64.encodeUrlSafe(hash)}.bin`
Input bytes: [01001000] [01100101] [01101100] H (72) e (101) l (108)6-bit groups: [010010] [000110] [010101] [101100] 18 6 21 44Base64 chars: S G V s (A-Z: 0-25, a-z: 26-51, 0-9: 52-61, +/: 62-63)
Input: H e l l oHex: 48 65 6c 6c 6fBinary: 01001000 01100101 01101100 01101100 01101111 ↓ 6-bit groups6-bits: 010010 | 000110 | 010101 | 101100 | 011011 | 000110 | 1111xxIndex: 18 | 6 | 21 | 44 | 27 | 6 | 60Base64: S | G | V | s | b | G | 8 | = (padding)Output: S G V s b G 8 =
Padding Rules:
Input length % 3 == 0: No padding (SGVs)
Input length % 3 == 1: Add == (SGVsbG8=)
Input length % 3 == 2: Add = (SGVsbGk=)
URL-safe encoding applies character substitutions after standard encoding: