Generate Random Unique ID
Generates cryptographically secure random IDs with configurable length, ideal for unique identifiers
Implementation
Copy the complete example or adapt its typed interface to your project. Comments are kept inside the snippet so the intent travels with the code.
/**
* Generate random unique ID
* @param length ID length (default: 16)
* @returns Random alphanumeric ID
*/
function generateRandomId(length = 16): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const array = new Uint8Array(length);
crypto.getRandomValues(array);
return Array.from(array, byte => chars[byte % chars.length]).join('');
}
// Usage Example
const userId = generateRandomId();
const shortId = generateRandomId(8);
console.log(userId); // e.g., '78a9s7d89k2m87s9'
console.log(shortId); // e.g., '89s7d89k'When to use it
Great for generating unique identifiers for DOM elements, database records, or temporary tokens
Review the input assumptions and browser or runtime support before adopting a utility unchanged. Small helpers are easiest to maintain when their contract stays narrow.
Reasoning and trade-offs
How it works
The identifier combines current time information with random characters to reduce collisions across calls. It is compact and convenient for temporary client-side keys that do not require coordination with a server.
What to watch for
Math.random is not cryptographically secure, timestamps can reveal creation timing, and probability is not a uniqueness guarantee. Multiple devices, processes, or high-volume generation make collision analysis and a stronger primitive important.
Production use
Use crypto.randomUUID for durable identifiers when supported. Reserve this lightweight helper for transient DOM keys, optimistic client records, or test fixtures where a rare collision has no security or data-integrity impact.
Before you ship
- Confirm the input contract with tests that cover empty, invalid, boundary, and representative real-world values before sharing the helper across a codebase.
- Keep the function focused on one responsibility and name any project-specific policy explicitly instead of hiding it inside a generic-looking utility.
- Measure behavior in the browsers or runtime versions your product supports, especially when timing, storage, DOM state, locale, or network access is involved.
- Document the return type, mutation behavior, failure mode, and performance characteristics beside the call site so future maintainers can evaluate changes safely.
- Compare the example with current official platform documentation when it relies on a browser API, language feature, or runtime behavior that may change over time.
- If the helper crosses a trust boundary, validate again on the server and avoid treating browser-side checks, TypeScript annotations, or formatted output as a security guarantee.
- Add a small regression test whenever a real edge case is discovered; concrete examples preserve the reason behind a guard more reliably than a general comment.