Generate a random string using Node crypto module

Return random bytes from node:crypto as a hex string.

JavaScriptNode.js Version 1.0.0 · MIT · .md

generate-a-random-string-using-node-crypto-module.js
import { randomBytes } from 'node:crypto';

function randomToken(bytes = 32) { return randomBytes(bytes).toString('hex'); }

Usage

usage.js
const secret = randomToken();
secret.length; // → 64
/^[0-9a-f]+$/.test(secret); // → true
randomToken(16); // e.g. '3f9c0e5b7a2d41e8b6c1f0a9d2e4b7c3'

Lines marked → were executed in Node.js 22, and each result was compared with the value shown. Lines marked e.g. are illustrative.

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.

Usage lines executed in Node.js 22; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.