How to Generate a Secure Random Number in Node.js


While you are working on your JavaScript apps, the moment will come when you need a secure random number. Generating it has been quite tricky in the past. Some people use Math.random whenever the need for a random number arises. Please don't do this if there is any chance for an attacker.

If you are generating random numbers for security reasons (e.g. verification codes), you should use a cryptographically secure random number. Fortunately, the crypto module has been extended in recent Node.js versions. So, now there's an easy way to do it in JavaScript.


  • Node.js (v14.10.0+ / v12.19.0+)

Generate a Secure Random Number Between min and max in JavaScript

Without further ado, let's generate our secure random number. First, import the crypto module:

const crypto = require("crypto");

Now, you have access to the randomInt function. randomInt takes up to three arguments.

Probably, you want to generate a random number in a given range. Therefore, you can specify the minimum (min) and maximum (max). Note that the minimum is inclusive and the maximum is exclusive. So, if you want to generate a number between 0 and 999,999 you'll have to pass 0 and 1000000.

// Synchronous
const n = crypto.randomInt(0, 1000000);

The third argument is optional. You can provide a callback function. Then, the random integer is generated asynchronously:

// Asynchronous
crypto.randomInt(0, 1000000, (err, n) => {
  if (err) throw err;

Good! Now, n is a secure random integer between 0 and 999999. For example, this could be used as a 6-digit verification code:

const verificationCode = n.toString().padStart(6, "0");


The changes in recent Node.js versions made generating secure random numbers easy. So, if you are generating random numbers to use as verification codes or for a secure random shuffle, you now know how to do it.

You May Also Be Interested in the Following Posts