The generateToken utility produces cryptographically secure random bytes from the native Web Cryptography API and encodes them as URL-safe Base64URL strings or clean Hexadecimal representations.
Usage
js
import { generateToken } from '@readytools/id';
// 32 bytes (256-bit entropy) Base64URL (Default)
const apiKey = generateToken(32, 'base64url');
// Returns: "vP9Q0Y_4xM8kL1nO7pR3tW5yZ2bC4dE6fG8hJ0lM9oQ"
// 16 bytes Hex string for HMAC signatures or webhook secrets
const webhookSecret = generateToken(16, 'hex');
// Returns: "a4f89012c45e67b93d8e01f2a3b4c5d6"⚡ Live Playground
generateToken()
Generating...
📏 Calculating...✨ Web Crypto Native
Comparison of Encodings
| Encoding | Byte to Char Ratio | URL-Safe | Best Used For |
|---|---|---|---|
| base64url | 4 chars per 3 bytes (33% overhead) | Yes (RFC 4648) | API Keys, Session Cookies, OAuth state, JWT signing tokens |
| hex | 2 chars per 1 byte (100% overhead) | Yes (0-9, a-f) | HMAC keys, Webhook signatures, Checksums |