# Generate a random string using Node crypto module

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

Canonical: https://1loc.dev/random/generate-a-random-string-using-node-crypto-module/
Version: 1.0.0
Runtime: Node.js 22
Verification: Usage lines executed in Node.js 22; no external services
Updated: 2026-10-28

## Implementation

```javascript
import { randomBytes } from 'node:crypto';

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

## Usage

```javascript
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.

## 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 does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/generate-a-random-string-using-node-crypto-module.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: See original repository history
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: 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.
