Generating a random alphanumeric string in JavaScript is common for temporary IDs, invite codes, or UI keys—but how you generate it depends heavily on whether you need speed or cryptographic security. Using Math.random() is fine for harmless UI labels, while crypto.getRandomValues() (or Node’s crypto) is the right choice for tokens, passwords, or security-sensitive codes.


1. Cryptographically Strong Random String (Recommended)

Use crypto.getRandomValues() (available in modern browsers and Node.js) with rejection sampling so every character in your alphabet has an equal chance without modulo bias:

function randomAlphanumeric(length = 12) {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const maxValidByte = Math.floor(256 / chars.length) * chars.length; // 248 for 62 chars
  const bytes = new Uint8Array(length * 2);
  let result = "";

  while (result.length < length) {
    crypto.getRandomValues(bytes);
    for (let i = 0; i < bytes.length && result.length < length; i++) {
      if (bytes[i] < maxValidByte) {
        result += chars[bytes[i] % chars.length];
      }
    }
  }

  return result;
}

console.log(randomAlphanumeric(12)); // e.g., "a8K3mP9xQ2vL"

2. Quick Non-Security Option (Math.random())

For non-sensitive client-side IDs or test fixtures where unpredictability does not matter, a loop over a character set is easy to read:

function fastRandomId(length = 8) {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";

  for (let i = 0; i < length; i++) {
    const index = Math.floor(Math.random() * chars.length);
    result += chars[index];
  }

  return result;
}

console.log(fastRandomId(8)); // e.g., "r7T2nB9k"

3. Common Traps to Avoid

  • Math.random().toString(36) shortcuts: toString(36) only uses lowercase letters a-z and digits 0-9 (not uppercase letters), has uneven trailing lengths due to floating-point rounding, and is not cryptographically secure.
  • Modulo bias on small alphabets: Taking byte % chars.length when 256 is not evenly divisible by chars.length makes early characters slightly more common unless you reject bytes at or above maxValidByte.
  • Confusing characters in human-read codes: If users type codes by hand (like promo or verification codes), consider omitting lookalikes such as 0, O, 1, I, and l.

TL;DR: Use crypto.getRandomValues() with rejection sampling for tokens or codes that need real randomness, avoid Math.random().toString(36) when you need mixed case or fixed lengths, and drop ambiguous characters if humans will type the string manually.

Are you generating a security token, a short human-readable code, or a temporary UI ID?