Developer Documentation
TypeScript
Updated September 19, 2026

Generate Secure Passwords in TypeScript

Generate cryptographically secure random passwords without modulo bias in TypeScript.

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 TypeScript API or a widely used package for this task.

Browser CSPRNG password#

TypeScript
1const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%";23function securePassword(length = ): string {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;10      output += alphabet[byte % alphabet.length];11      if (output.length === length) break;12    }13  }14  return output;15}

Common Operations#

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

Typed options#

TypeScript
1type PasswordOptions = { length: number; alphabet: string };23function assertOptions(options: PasswordOptions): void {4  if (options.length < ) throw new RangeError("length must be positive");5  if (options.alphabet.length <  || options.alphabet.length > ) {6    throw new RangeError("alphabet must contain 2..256 characters");7  }8}

Important Notes#

Avoid Math.random() for passwords and recovery codes; use Web Crypto or Node.js crypto.

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: