How to generate random strings in Node.js

Generating secure random strings is essential for creating unique identifiers, authentication tokens, and session IDs in Node.js applications. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented random string generation in countless Node.js authentication systems and API services. From my 25 years of experience in web development and 11 years with Node.js, the most secure and reliable approach is to use Node.js built-in crypto.randomBytes() method. This method provides cryptographically strong random values suitable for security-sensitive applications.

Use crypto.randomBytes() with toString() to generate cryptographically secure random strings.

const crypto = require('crypto')

function generateRandomString(length = 32) {
  return crypto.randomBytes(Math.ceil(length / 2))
    .toString('hex')
    .slice(0, length)
}

function generateBase64String(length = 32) {
  return crypto.randomBytes(Math.ceil(length * 3 / 4))
    .toString('base64')
    .slice(0, length)
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '')
}

// Usage examples
const token = generateRandomString(32)
console.log(token) // 'a1b2c3d4e5f6...'

const urlSafeToken = generateBase64String(32)
console.log(urlSafeToken) // 'AbC123XyZ...'

The crypto.randomBytes() method generates cryptographically secure random bytes that can be converted to different string formats. Using toString('hex') creates a hexadecimal string with characters 0-9 and a-f. The toString('base64') method creates base64 strings, which are URL-safe after replacing problematic characters. The length parameter controls the final string length, but you need to generate more bytes than needed since each byte creates multiple characters in the output.

This is the same secure random string generation approach we use in CoreUI backend services for API keys and session tokens. For simple non-security use cases, you can use Math.random().toString(36).substring(2), but always prefer crypto methods for authentication tokens.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author