How to Generate Random Strings in TypeScript (4 Ways)

A client running a Chicago outdoor-gear store asked me to generate random strings in TypeScript for a $15.00-off coupon, receipt order codes and password-reset tokens.

The snippet you’ll usually copy, Math.random().toString(36), gives you neither a fixed length nor safe randomness.

Quick answer: pick characters from a string with Math.random() for test data, but use crypto.getRandomValues() or crypto.randomUUID() for anything a user could guess.

In this tutorial, I’ll show you how to generate random string in TypeScript four ways. I ran everything with TypeScript 7.0.2 and Node.js v22.22.2 in strict mode.

How Do You Generate a Random String with Math.random()?

Start with a helper that takes a length and a character set, fine for test data and coupons:

const ALPHANUM =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const COUPON = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";

function randomString(length: number, chars = ALPHANUM): string {
  let out = "";
  for (let i = 0; i < length; i++) {
    out += chars[Math.floor(Math.random() * chars.length)];
  }
  return out;
}

const ref = randomString(10);
const coupon = `SAVE15-${randomString(6, COUPON)}`;
console.log("Ref:", ref, ref.length);
console.log("Coupon:", coupon, coupon.length);

Output:

Ref: wM3A7RRzpK 10
Coupon: SAVE15-UL4BPY 13

Each run prints a new 10-character ref and a 13-character SAVE15- coupon.

VS Code running a TypeScript randomString() helper; the terminal shows a 10-character ref and a 13-character SAVE15 coupon
Values change on every run; the lengths stay 10 and 13.

How does this code work?

Math.floor(Math.random() * chars.length) picks a random index, and the for loop in TypeScript repeats that length times.

The COUPON set skips 0, O, 1 and I, so you won’t get support tickets about misread codes.

Secure Random Strings with crypto.getRandomValues()

A guessable order code exposes someone else’s order, so use the Web Crypto API:

const CODE_CHARS = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; // 32

function secureString(length: number, chars = CODE_CHARS): string {
  if (256 % chars.length !== 0) {
    throw new Error(`${chars.length} chars would skew the odds`);
  }
  const bytes = crypto.getRandomValues(new Uint8Array(length));
  let out = "";
  for (const b of bytes) out += chars[b % chars.length];
  return out;
}

const code = `LV-${secureString(8)}`;
console.log("Order code:", code, code.length);
try {
  secureString(8, "ABCDEFGHIJ");
} catch (err) {
  console.log("Error:", (err as Error).message);
}

Output:

Order code: LV-0GAE9G60 11
Error: 10 chars would skew the odds

You get LV- plus 8 characters (11 total), then the guard rejects the 10-character set.

VS Code running a TypeScript secureString() helper with crypto.getRandomValues(); the terminal shows an 11-character LV order code and the charset error
A crypto-backed order code, then the guard catching a bad charset.

How does this code work?

getRandomValues() fills a Uint8Array with secure bytes (0-255), and b % chars.length maps each to a character.

That modulo is only fair when the set size divides 256, so I use 32 characters. A 10-character set would favor its first six.

Note: you don’t import crypto; it’s global in browsers and Node.js 19+.

Generate UUIDs and Hex Tokens in TypeScript

For order IDs and reset links I skip custom formats entirely:

const orderId = crypto.randomUUID();
console.log("Order ID:", orderId, orderId.length);

function hexToken(bytes: number): string {
  const buf = crypto.getRandomValues(new Uint8Array(bytes));
  return Array.from(buf, (b) => b.toString(16).padStart(2, "0"))
    .join("");
}

const reset = hexToken(16);
console.log("Reset token:", reset, reset.length);
console.log("Hex only:", /^[0-9a-f]{32}$/.test(reset));

Output:

Order ID: 4380a5da-2be5-4dc8-9e4c-ceb91c6bf70f 36
Reset token: 3985ac8674e91672cfd990de6f74624f 32
Hex only: true

The UUID is always 36 characters, the token 32 hex characters, and the check prints true.

VS Code running crypto.randomUUID() and a hexToken() helper; the terminal shows a 36-character UUID, a 32-character hex token and Hex only: true
A 36-character UUID and a 32-character hex reset token.

How does this code work?

randomUUID() returns a version 4 UUID, so the third group always starts with 4. My TypeScript UUID guide covers validation.

In hexToken(), toString(16) gives hex and padStart(2, "0") keeps two digits, a trick I use when I convert a number to a string in TypeScript.

Why the toString(36) Shortcut Gives the Wrong Length

Here’s the popular toString(36) trick with fixed inputs:

// toString(36) trick with fixed inputs
for (const n of [0.5, 0.25, 0.7364829174]) {
  const s = n.toString(36).slice(2);
  console.log(n, "->", JSON.stringify(s), "length", s.length);
}

Output:

0.5 -> "i" length 1
0.25 -> "9" length 1
0.7364829174 -> "qihchpd18ls" length 11

0.5 gives i, 0.25 gives 9, and only the long number yields 11 characters.

Lengths drift, so check them; comparing strings in TypeScript helps when testing for duplicates.

Common Errors When Generating Random Strings and How to Fix Them

The error I see most is a length that arrives as text from a form field:

declare function randomString(length: number): string;

const lengthInput = "12"; // read from a form field
const code = randomString(lengthInput);

Output:

rand_form.ts(4,27): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
VS Code flagging randomString(lengthInput): red squiggle, Problems badge and tsc error TS2345, string not assignable to number
tsc stops at the string length before anything runs.

Fix it with randomString(Number(lengthInput)). To check a value first, see checking the type of a variable in TypeScript.

If you’re saving codes users paste back in, remove spaces from the string first.

I’d keep these TypeScript string guides open next:

Frequently Asked Questions

How do I generate a random string in TypeScript?

Pick length characters with Math.random(), or crypto.getRandomValues() for secure codes.

Is Math.random() safe for passwords or tokens?

No. Use crypto.getRandomValues() or crypto.randomUUID().

How do I make a random alphanumeric string of a fixed length?

Use a helper like randomString(10), not toString(36).

Does crypto.randomUUID() work in Node.js?

Yes, in Node.js 19+ as a global; it returns 36 characters.

Do I need an npm package for random strings?

Usually not; built-in crypto covers it.

Where is crypto.getRandomValues() documented?