Generate a random string using Node crypto module
Return random bytes from node:crypto as a hex string.
import { randomBytes } from 'node:crypto';
function randomToken(bytes = 32) { return randomBytes(bytes).toString('hex'); }
Usage
const secret = randomToken();
secret.length; // → 64
/^[0-9a-f]+$/.test(secret); // → true
randomToken(16); // e.g. '3f9c0e5b7a2d41e8b6c1f0a9d2e4b7c3'
Know the limits
- 32 bytes are 256 bits of entropy: 64 hex characters. toString("base64url") gives a shorter token for URLs.
- Use it for secrets you generate: webhook signing secrets, unsubscribe or password-reset tokens. Store a hash of tokens you only need to compare.
- The original used require("crypto"), which is unavailable in ES modules; this version imports node:crypto.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Generate a random string using Node crypto module from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Imports node:crypto, which works in ES modules, instead of require. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Generate a random boolean — Return true or false with equal probability.
- Generate a random floating point number in given range — Scale Math.random into [min, max).
- Generate a random hex color — Return a #rrggbb color from 24 random bits.