Skip to content
GreenSnippets

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
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

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.