Developer Documentation
JavaScript
Updated September 19, 2026

Generate Secure Passwords in JavaScript

Generate cryptographically secure random passwords without modulo bias in JavaScript.

A password generator should draw randomness from the operating system or platform CSPRNG. Do not use predictable pseudo-random functions intended for simulations or UI effects.

Quick Start#

The following example uses the standard JavaScript API or a widely used package for this task.

Browser CSPRNG password#

JavaScript
1const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%";23function securePassword(length = ) {4  const limit =  - ( % alphabet.length);5  let output = "";6  while (output.length < length) {7    const bytes = crypto.getRandomValues(new Uint8Array(length));8    for (const byte of bytes) {9      if (byte >= limit) continue; // rejection sampling avoids modulo bias10      output += alphabet[byte % alphabet.length];11      if (output.length === length) break;12    }13  }14  return output;15}1617console.log(securePassword());

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Generate a random PIN#

JavaScript
1function securePin(digits = ) {2  const max =  ** digits;3  const array = new Uint32Array();4  const limit =  **  - (( ** ) % max);5  do crypto.getRandomValues(array); while (array[] >= limit);6  return String(array[] % max).padStart(digits, "0");7}

Important Notes#

Password generation and password storage are separate concerns. Store passwords with a password hashing function, never reversible encoding or a plain SHA digest.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement Password in other languages: