How to Generate Secure Random Tokens in Node.js
Generate session ids, reset links and API keys with crypto.randomBytes, randomUUID and randomInt, and learn why Math.random must never make a token.

Every application eventually needs a value that nobody can guess: a password reset link, a session identifier, an API key, an email verification code, a CSRF token. The requirement is the same each time. An attacker who has seen a thousand of your tokens must not be able to predict the next one, and an attacker who guesses must be astronomically unlikely to hit a valid one. This post shows how to generate such tokens in Node.js 26 with the built-in node:crypto module, how to encode them for URLs, how to store them, and how to compare them without leaking timing information. It also explains why Math.random() is the wrong tool, because that mistake is the most common one.
Why Math.random is not allowed
Math.random() returns a number between 0 and 1 from a pseudo-random generator that is designed for speed and statistical spread, not for secrecy. The ECMAScript specification only requires an implementation-defined algorithm with approximately uniform distribution, and V8 uses a generator whose internal state can be recovered from a handful of outputs. Once an attacker can recover the state, every later value is predictable. A token built from it is a guess waiting to be confirmed.
A cryptographically secure pseudo-random number generator (CSPRNG) is different. It is seeded from the operating system's entropy source and designed so that past output reveals nothing useful about future output. Node.js exposes the operating system's generator through node:crypto, documented in the crypto module reference.
// Do not do this for anything secret.
const token = Math.random().toString(36).slice(2);
console.log(typeof token);stringThe code runs and returns a string that looks random. That is the danger: nothing fails, and the weakness is invisible until someone attacks it. The rest of this post replaces that line with something safe.
The default choice: randomBytes
crypto.randomBytes(size) returns a Buffer of size cryptographically strong random bytes. Pick the size from the strength you need, not from how long the string looks. Sixteen bytes is 128 bits of randomness, which is enough that guessing is infeasible. Thirty-two bytes is 256 bits, which is the common choice for long-lived secrets such as API keys.
import { randomBytes } from "node:crypto";
const token = randomBytes(32).toString("hex");
console.log(token.length);
console.log(/^[0-9a-f]{64}$/.test(token));64
trueThe toString("hex") call turns each byte into two hexadecimal characters, so 32 bytes become 64 characters. The value itself differs on every run, so the output shows only its length and shape. Hex is safe in URLs, filenames and headers, which makes it a reasonable default, but it spends two characters per byte.
Shorter strings with base64url
Base64 packs six bits into every character instead of four, so the same 32 bytes fit in 43 characters. Plain base64 uses +, / and =, which need escaping in a URL. The base64url encoding replaces them with - and _ and drops the padding, so the result can sit in a path or query string untouched. Node.js supports it as a Buffer encoding, described in the Buffer documentation.
import { randomBytes } from "node:crypto";
const token = randomBytes(32).toString("base64url");
console.log(token.length);
console.log(/^[A-Za-z0-9_-]{43}$/.test(token));43
trueThirty-two bytes is 256 bits, which is not a multiple of six, so the last character carries only four bits of information and the string has no padding. You do not need to care about that detail. What matters is that the entropy is 256 bits regardless of how the bytes are printed.
Asynchronous and synchronous forms
randomBytes has a callback form and a synchronous form. The synchronous call can block if the operating system has not yet gathered enough entropy, which is a real concern only very early in the boot of a machine. On a running server it returns immediately. The callback form does the work on the thread pool. Most code uses the synchronous call for small sizes, and that is fine.
If you prefer promises, wrap the callback form with util.promisify:
import { randomBytes } from "node:crypto";
import { promisify } from "node:util";
const randomBytesAsync = promisify(randomBytes);
const buf = await randomBytesAsync(16);
console.log(buf.length);
console.log(buf.toString("hex").length);16
32For a 16-byte token the synchronous version costs almost nothing, so the asynchronous form is only worth it when you request very large buffers.
Identifiers: randomUUID
When the requirement is a unique identifier rather than a secret, crypto.randomUUID() returns a version 4 UUID string using a CSPRNG. It is documented in the randomUUID reference.
import { randomUUID } from "node:crypto";
const id = randomUUID();
console.log(id.length);
console.log(id[14]);
console.log(/^[0-9a-f-]{36}$/.test(id));36
4
trueA version 4 UUID carries 122 random bits, because six bits are fixed to mark the version and variant. That is enough to be unguessable in practice, and many systems do use UUIDs as session ids. Still, if the value is an authorisation secret, prefer randomBytes with an explicit size, because a UUID is a format that people paste into logs and URLs without thinking of it as a secret, and the dashes and fixed digits add nothing.
Numbers and codes: randomInt
A six-digit one-time code looks like a job for randomInt. Never write Math.floor(randomBytes(1)[0] / 256 * 10) or take a random byte modulo ten. A byte has 256 values, which does not divide evenly by ten, so digits 0 to 5 appear slightly more often than 6 to 9. That skew is called modulo bias, and it is a real, if small, weakness. crypto.randomInt([min, ]max) avoids it by rejecting values that would cause bias. The upper bound is exclusive.
import { randomInt } from "node:crypto";
const code = String(randomInt(0, 1_000_000)).padStart(6, "0");
console.log(code.length);
console.log(/^\d{6}$/.test(code));6
trueThe padStart call keeps leading zeros, so the code "004217" is not shortened to four digits. A six-digit code has only a million values, so it is only safe when you also limit attempts and give it a short lifetime. The randomness is sound, but the keyspace is small, which is a different problem from predictability.
The Web Crypto route
globalThis.crypto exposes the Web Crypto API in Node.js, the same one browsers have. crypto.getRandomValues(typedArray) fills a typed array with secure random values, and crypto.randomUUID() exists there too. This is useful when the same code must run in Node.js, a browser and an edge runtime.
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
const token = Buffer.from(bytes).toString("base64url");
console.log(bytes.length);
console.log(token.length);16
22Sixteen bytes encode to 22 base64url characters, since 16 times 8 is 128 bits and 128 divided by 6 rounds up to 22. getRandomValues limits a single call to 65,536 bytes, so large requests need a loop or randomBytes.
Storing and comparing tokens
Generating a good token is half the job. Treat a reset token or API key like a password. Store only a hash of it, so a database leak does not hand out working credentials. A fast hash such as SHA-256 is appropriate here, unlike for passwords, because the token already has 128 or more bits of entropy and cannot be brute-forced from its hash.
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
const hash = (token) => createHash("sha256").update(token).digest();
const token = randomBytes(32).toString("base64url");
const stored = hash(token);
function verify(candidate) {
const candidateHash = hash(candidate);
return timingSafeEqual(candidateHash, stored);
}
console.log(verify(token));
console.log(verify("not-the-token"));true
falseThe user receives token and the database keeps only stored. When a request arrives, you hash the candidate and compare the two digests. timingSafeEqual compares two buffers of equal length in constant time, so an attacker cannot learn how many leading bytes matched from how long the response took. Because both values are SHA-256 digests, they are always 32 bytes, so the length requirement is met. The function throws if the lengths differ, which is why you hash first and compare digests rather than comparing raw strings of unknown size.
Expiry and single use
A token is only as safe as its lifecycle. Store an expiry timestamp next to the hash, reject expired tokens, and delete the row on first successful use. For a reset link, 15 to 60 minutes is common. For an email verification link, a day is typical. Those are conventions, not requirements from Node.js, so choose values that fit your threat model.
const record = {
hash: "…stored digest…",
expiresAt: Date.UTC(2026, 10, 20, 12, 30),
usedAt: null,
};
function isUsable(rec, now) {
return rec.usedAt === null && now < rec.expiresAt;
}
console.log(isUsable(record, Date.UTC(2026, 10, 20, 12, 0)));
console.log(isUsable(record, Date.UTC(2026, 10, 20, 13, 0)));true
falseChecking usedAt and the expiry in one function keeps the rule in one place, so every route that accepts a token applies it the same way.
Common mistakes
Truncating a token to look tidy. Cutting 32 bytes to eight characters throws away most of the entropy. Choose the byte count first and let the string be as long as it needs to be.
Deriving tokens from user data. A hash of an email plus a timestamp is predictable, because the inputs are known. Tokens must come from the random generator and nothing else.
Logging tokens. Request logs, error trackers and analytics tools keep what they see. Keep tokens out of URLs that get logged, or redact them.
Reusing one token for several purposes. A password reset token should not also work as a login token. Store a purpose with each hash.
**Comparing with
===.** Plain string comparison returns as soon as it finds a difference, so the response time leaks information. UsetimingSafeEqualon digests.


