Skip to content

Base64 Module

The std/base64 module provides functions for encoding and decoding data in standard and URL-safe Base64 formats.

import { base64 } from "std/base64";

Encodes a string to standard Base64.

const encoded = base64.encode("Hello, World!");
println(encoded); // "SGVsbG8sIFdvcmxkIQ=="

Decodes a standard Base64 string back to the original.

const decoded = base64.decode("SGVsbG8sIFdvcmxkIQ==");
println(decoded); // "Hello, World!"

Encodes a string to URL-safe Base64 (uses - and _ instead of + and /, no padding).

const encoded = base64.urlEncode("Hello+World/Test=");
println(encoded); // URL-safe encoded string

Decodes a URL-safe Base64 string.

const decoded = base64.urlDecode(encoded);
println(decoded); // "Hello+World/Test="

Returns true if the string is valid standard Base64.

println(base64.isValid("SGVsbG8=")); // true
println(base64.isValid("not valid!!!")); // false

These functions work with Buffer objects directly, enabling binary protocol implementations such as SCRAM-SHA-256 authentication.

Encodes a raw byte Buffer to a standard Base64 string.

import { base64 } from "std/base64"
import { Buffer } from "std/buffer"
var buf = Buffer.fromString("Hello")
var encoded = base64.encodeBuffer(buf)
println(encoded) // "SGVsbG8="

base64.decodeToBuffer(encoded: string): Buffer

Section titled “base64.decodeToBuffer(encoded: string): Buffer”

Decodes a standard Base64 string to a raw byte Buffer.

import { base64 } from "std/base64"
import { Buffer } from "std/buffer"
var buf = base64.decodeToBuffer("SGVsbG8=")
println(buf.toString("utf8")) // "Hello"
println(buf.length()) // 5
import { base64 } from "std/base64";
// Standard encode/decode
const secret = "my-api-key-12345";
const encoded = base64.encode(secret);
println("Encoded: " + encoded);
const decoded = base64.decode(encoded);
println("Decoded: " + decoded);
// URL-safe for query params
const urlSafe = base64.urlEncode("data+with/special=chars");
println("URL-safe: " + urlSafe);
// Validation
if (base64.isValid(encoded)) {
println("Valid base64!");
}