DEV Community

Alessio Michelini
Alessio Michelini

Posted on

Random numbers in Node.js with Crypto

Until not long ago the way to get a random number in JavaScript was to use Math.random(), which it will give you a "random" number between 0 and 1, and if you needed to have a number between 0 and 10, you probably did something like this:

const number = Math.floor(Math.random() * 10);
Enter fullscreen mode Exit fullscreen mode

But the are a few problems with the above.

The first thing is that is not cryptographically secure, to a point that you can even predict the value you are going to get, and you can read an interesting stackoverflow answer here if you want to know more.
The second thing is that is rather clucky as a solution, you are literally getting a number like 0.7478816910932602, then multiply by 10 and just use Math.floor to get rid of the decimal numbers.
There must be a better way to do it, and indeed you do.

While in the browsers you can use Crypto.getRandomValues (more info here), with Node.js you can access to the crypto library, which gives you access to a much more complete set of tools than the browser has, and it simplify actions like "get a random number between 1 and 10".
To replicate the code we had at the beginning, you just need to use the crypto.randomInt(min, max) method, so our code will look like this:

const { randomInt } = require('crypto');

const number = randomInt(0,10);
Enter fullscreen mode Exit fullscreen mode

And the crypto library is by design cryptographically secure and it's much simpler to use in my opinion.
Here another example on how to use it randomly select a value from an array:

const { randomInt } = require('crypto');

const colours = ['red', 'blue', 'green', 'yellow'];

const pick = colours[randomInt(0, colours.length - 1)];

console.log(pick); // blue
Enter fullscreen mode Exit fullscreen mode

Note: the crypto library was added from v14.10.0 and v12.19.0 onwards.

Top comments (0)