← Back to Blog
2026-03-092 min readby DevUtilz

Random String Generator Guide

RandomStringSecurityTools

Random String Generator Guide

Random strings are used for tokens, session IDs, verification codes, and more. Here's how to generate them securely.

Basic Random String

function randomString(length) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

Problem: Math.random() is not cryptographically secure!

Secure Random Strings

// Using crypto API (recommended)
function secureRandomString(length) {
  const array = new Uint8Array(length);
  crypto.getRandomValues(array);
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  return Array.from(array, byte => chars[byte % chars.length]).join('');
}

// Using crypto.randomUUID()
const token = crypto.randomUUID(); // 36-char UUID

Different Character Sets

const sets = {
  alphanumeric: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
  alpha: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
  numeric: '0123456789',
  hex: '0123456789abcdef',
  ascii: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
};

function generate(length, charset) {
  const array = new Uint8Array(length);
  crypto.getRandomValues(array);
  return Array.from(array, byte => charset[byte % charset.length]).join('');
}

Common Use Cases

1. Session Tokens

const sessionToken = secureRandomString(32);
// Example: aB3xK9mNpQrS5tUvW2yZ8hF4gH6jL1kP

2. Verification Codes

const code = generate(6, '0123456789');
// Example: 482931

3. API Keys

const apiKey = 'sk_' + secureRandomString(48);
// Example: sk_aB3xK9mNpQrS5tUvW2yZ8hF4gH6jL1kP

4. Password Reset Tokens

const resetToken = secureRandomString(64);
// 64 characters, high entropy

Using nanoid Library

import { nanoid } from 'nanoid';

// Default (21 chars, URL-safe)
nanoid(); // 'V1StGXR8_Z'

// Custom length
nanoid(16); // 'qwErTyUiOpAsDfGh'

// No symbols (alphanumeric only)
nanoid(16, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');

Security Best Practices

  1. Always use crypto.getRandomValues() - Not Math.random()
  2. Use appropriate length - 32+ for tokens, 6 for codes
  3. Use URL-safe characters - For tokens in URLs
  4. Store securely - Don't log sensitive tokens

Length vs Entropy

| Length | Entropy (bits) | Use Case | |--------|---------------|----------| | 6 | ~35 | 4-digit equivalent, verification codes | | 16 | ~95 | Session IDs | | 32 | ~190 | API keys | | 64 | ~380 | Reset tokens |

Common Mistakes

// Wrong - predictable
const bad = Math.random().toString(36).substring(2, 10);

// Correct - secure
const good = secureRandomString(8);

Conclusion

Always use cryptographically secure random functions for security-sensitive applications. Use appropriate lengths based on the use case.