How to Generate Random Bytes in Node.js Easily
In Node.js, you can generate random bytes using the
crypto module's randomBytes function. It returns a buffer of cryptographically strong random bytes, which you can use directly or convert to strings like hex or base64.Syntax
The crypto.randomBytes(size[, callback]) function generates random bytes where:
- size: Number of bytes to generate.
- callback (optional): If provided, the function works asynchronously and calls back with the result.
Without a callback, it returns a Buffer synchronously.
javascript
import { randomBytes } from 'crypto'; // Synchronous usage const buf = randomBytes(16); // Asynchronous usage randomBytes(16, (err, buf) => { if (err) throw err; // use buf });
Example
This example shows how to generate 16 random bytes synchronously and print them as a hex string.
javascript
import { randomBytes } from 'crypto'; const bytes = randomBytes(16); console.log('Random bytes in hex:', bytes.toString('hex'));
Output
Random bytes in hex: e3b0c44298fc1c149afbf4c8996fb924
Common Pitfalls
Common mistakes include:
- Not importing
cryptocorrectly in ESM modules. - Using
randomByteswithout handling errors in asynchronous calls. - Confusing the output buffer with a string; always convert with
toString('hex')or similar.
javascript
import { randomBytes } from 'crypto'; // Wrong: expecting string directly const wrong = randomBytes(8); console.log(wrong); // prints a Buffer, not a string // Right: convert buffer to hex string const right = randomBytes(8); console.log(right.toString('hex'));
Output
<Buffer ...>
8f2a4b1c9d7e3f0a
Quick Reference
Tips for using crypto.randomBytes:
- Use synchronous version for simple scripts.
- Use asynchronous version in servers to avoid blocking.
- Convert buffers to strings with
toString('hex')ortoString('base64'). - Always handle errors in async calls.
Key Takeaways
Use Node.js built-in crypto module's randomBytes to generate secure random bytes.
randomBytes(size) returns a Buffer; convert it to string with toString('hex') or 'base64'.
Use async randomBytes with a callback to avoid blocking in server apps.
Always handle errors in asynchronous randomBytes calls.
Import crypto correctly using ESM syntax: import { randomBytes } from 'crypto';