Generate secure random IDs and integers
Create UUIDs, random integers in a range and URL-safe tokens with the Web Crypto API instead of Math.random.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
const randomUUID = () => crypto.randomUUID();
function randomInt(min, max) {
// inclusive range
const range = max - min + 1;
const limit = Math.floor(0x100000000 / range) * range;
const buffer = new Uint32Array(1);
do {
crypto.getRandomValues(buffer);
} while (buffer[0] >= limit);
return min + (buffer[0] % range);
}
function randomToken(bytes = 16) {
const buffer = crypto.getRandomValues(new Uint8Array(bytes));
return btoa(String.fromCharCode(...buffer)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}Example / expected output
randomUUID() // "3b241101-e2bb-4255-8caf-4136c566a962"
randomInt(1, 6) // 1..6
randomToken() // "q3Vh0m1eY8bZc2s5Jx9Lrw"How it works
Math.random() is predictable and must never be used for tokens or IDs that guard anything. crypto.randomUUID() and crypto.getRandomValues() work in browsers and Node.js. The integer helper uses rejection sampling to avoid modulo bias.
Related snippets
- PHP Tested
Generate a secure random token in PHP
Create unpredictable tokens for password resets, API keys and CSRF protection with random_bytes.
- PHP Tested
Validate emails and URLs in PHP
Use filter_var to validate email addresses and http(s) URLs, with an allow-list for schemes.
- Python Tested
Sign API requests with HMAC-SHA256
Create and verify a timestamped signature over the method, path and body so requests cannot be forged or replayed.
- PHP Tested
Escape output to prevent XSS in PHP
A short helper around htmlspecialchars with the right flags for HTML text and attribute values.

