crypto.randomBytes() Method in Node.js

The crypto.randomBytes() method generates cryptographically strong pseudo-random data in Node.js. This method ensures sufficient entropy before completion, typically taking only a few milliseconds to generate secure random bytes.

Syntax

crypto.randomBytes(size, [callback])

Parameters

The parameters are described below:

  • size - Specifies the number of bytes to generate. Must not exceed 2**31 - 1.

  • callback - Optional callback function called if an error occurs. If omitted, the method runs synchronously.

Asynchronous Example

Using crypto.randomBytes() with a callback for asynchronous operation:

// Importing the crypto module
const crypto = require('crypto');

crypto.randomBytes(64, (err, buf) => {
  if (err) throw err;
  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});
64 bytes of random data: eb2bcebb999407286caea729998e7fa0c089178f8ca43857e73ea3ff66dbe1852af24a4b0199be9192798a3f8ad6d6475db3621cfacf38dcb0fba5d77d73aaf5

Synchronous Example

Using crypto.randomBytes() without a callback for synchronous operation:

// Importing the crypto module
const crypto = require('crypto');

const buffer = crypto.randomBytes(256);
console.log(
  `${buffer.length} bytes of random data: ${buffer.toString('base64')}`);
256 bytes of random data: n7yfRMo/ujHfBWSF2VFdevG4WRbBoG9Fqwu51+/9ZBUV6Qo88YG7IbcEaIer+g+OgjMv4RyNQ6/67aF5xWmkOR3oA6J6bdAJ1pbstTuhIfItF1PQfP26YXk1QlaoKy/YJxPUngyK4kNG9O04aret4D+2qIq9BUaQcv+R9Xi014VKNUDZ+YQKEaLHBhJMq6JgehJ56iNbdNJ4+PN7SQwjNdZ8gS76izAwYsSZ7Kuyx2VzdXIKsLmjleuJ2DZ7/6Yyn8WM9463dhuh0KQ5nwFbgzucvjmdvDjBlGFZBGlKs6AXqYh+0Oe6Ckkv3OpnXOJs+GExbmnvjaeDQ03khpdJfA==

Common Use Cases

The crypto.randomBytes() method is commonly used for:

  • Generating secure tokens and session IDs
  • Creating cryptographic keys and salts
  • Initializing random seeds for encryption algorithms

Conclusion

The crypto.randomBytes() method provides cryptographically secure random data generation in Node.js. Use the asynchronous version for non-blocking operations or the synchronous version when immediate results are needed.

Updated on: 2026-03-15T23:19:00+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements