How to generate secure random numbers in JavaScript
Generating truly random numbers for security purposes requires cryptographically secure methods, not just Math.random().
As the creator of CoreUI, with over 25 years of experience building secure web applications since 2000, I’ve implemented secure random number generation for authentication tokens, session IDs, and security features countless times.
The standard approach is to use the Web Crypto API’s crypto.getRandomValues() method, which provides cryptographically strong random values suitable for security-sensitive operations.
This method is supported in all modern browsers and Node.js environments.
Use crypto.getRandomValues() to generate cryptographically secure random numbers.
const array = new Uint32Array(1)
crypto.getRandomValues(array)
const secureRandom = array[0]
Here crypto.getRandomValues() fills the Uint32Array with cryptographically secure random values. The array[0] contains a random 32-bit unsigned integer. This method uses the operating system’s random number generator, which is suitable for cryptographic operations.
Generating Random Numbers in a Range
To generate a secure random number within a specific range, use this approach.
function getSecureRandomInRange(min, max) {
const range = max - min
const array = new Uint32Array(1)
crypto.getRandomValues(array)
return min + (array[0] % (range + 1))
}
const random = getSecureRandomInRange(1, 100)
This function generates a random number between min and max inclusively. The modulo operator ensures the result falls within the specified range. For cryptographic purposes, this method provides sufficient randomness.
Generating Random Bytes
For tokens and session IDs, generate random bytes and convert them to strings.
function generateSecureToken(length) {
const array = new Uint8Array(length)
crypto.getRandomValues(array)
return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('')
}
const token = generateSecureToken(32)
Here Uint8Array creates an array of bytes. The Array.from() converts each byte to a two-digit hexadecimal string. The result is a 64-character hexadecimal token (32 bytes × 2 characters per byte).
Generating Random Floating-Point Numbers
To generate secure random floating-point numbers between 0 and 1, use this method.
function getSecureRandomFloat() {
const array = new Uint32Array(1)
crypto.getRandomValues(array)
return array[0] / (0xFFFFFFFF + 1)
}
const randomFloat = getSecureRandomFloat()
This divides the random 32-bit integer by the maximum possible value plus one. The result is a floating-point number between 0 (inclusive) and 1 (exclusive), similar to Math.random() but cryptographically secure.
Node.js Implementation
In Node.js, use the crypto module for secure random number generation.
const crypto = require('crypto')
function getSecureRandomNumber() {
const buffer = crypto.randomBytes(4)
return buffer.readUInt32BE(0)
}
const random = getSecureRandomNumber()
The crypto.randomBytes() generates cryptographically secure random bytes. The readUInt32BE() reads them as a 32-bit unsigned integer in big-endian format. This method is equivalent to the browser’s crypto.getRandomValues().
Generating Random UUIDs
For generating unique identifiers, use the UUID generation method.
function generateSecureUUID() {
const array = new Uint8Array(16)
crypto.getRandomValues(array)
array[6] = (array[6] & 0x0f) | 0x40
array[8] = (array[8] & 0x3f) | 0x80
const hex = Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('')
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
}
const uuid = generateSecureUUID()
This generates a version 4 UUID according to RFC 4122. The bit manipulation ensures the UUID follows the correct format. The result is a standard UUID string like 550e8400-e29b-41d4-a716-446655440000.
Best Practice Note
This is the same secure random generation approach we use in CoreUI components for generating unique component IDs and handling security-sensitive operations. Never use Math.random() for security purposes - it’s not cryptographically secure and can be predicted. Always use crypto.getRandomValues() in browsers or crypto.randomBytes() in Node.js for authentication tokens, session IDs, passwords, encryption keys, or any security-critical random values. For production applications requiring secure token generation, consider using CoreUI’s authentication components which implement these security best practices by default.



