Secure random token in Node.js with crypto

Secure Random Token in Node.js with Crypto

If you are working with Node.js and need to generate a secure random token, you can use the built-in crypto module. This module provides cryptographic functionality that includes a pseudo-random number generator (PRNG) that can be used to generate secure random tokens.

Generating a Secure Random Token

To generate a secure random token, you can use the crypto.randomBytes() method. This method generates a cryptographically secure pseudo-random data with the specified number of bytes. Here is an example of how to use it:

const crypto = require('crypto');

const generateToken = (length) => {
  return crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0, length);

const token = generateToken(16);

The above code generates a 16-byte (32-character) secure random token using the crypto.randomBytes() method. The Math.ceil(length/2) argument makes sure that we generate enough random bytes to cover the specified length of the token. The toString('hex') method converts the generated bytes to a hexadecimal string, and the slice(0, length) method trims the string to the desired length.

Using a Cryptographically Secure PRNG

To ensure that your random tokens are truly secure, it is important to use a cryptographically secure PRNG. The crypto module provides a built-in PRNG that is considered to be cryptographically secure, so it is recommended to use it when generating random tokens.

Here is an example of how to use the crypto.randomInt() method to generate a cryptographically secure random integer:

const crypto = require('crypto');

const generateRandomNumber = (min, max) => {
  return crypto.randomInt(min, max + 1);

const randomNum = generateRandomNumber(1, 10);

The above code generates a cryptographically secure random integer between 1 and 10 using the crypto.randomInt() method. The min and max arguments specify the range of numbers to generate.


The crypto module in Node.js provides a simple way to generate secure random tokens using a cryptographically secure PRNG. By using this module, you can ensure that your random tokens are truly unpredictable and cannot be easily guessed or generated by an attacker.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]