uuid
The uuid utility generates a cryptographically strong Universally Unique Identifier (UUID) version 4, as specified in RFC 4122.
Implementation
View Source Code
ts
/**
* Generates a unique identifier.
*
* @example
* ```ts
* uuid(); // a unique identifier, e.g., '22a746d0-08be-4aff-bbc2-4deddf0914e0'
* ```
*
* @returns A unique identifier.
*/
export function uuid(): string {
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
return crypto.randomUUID();
}
return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/x/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}Features
- Isomorphic: Works in both Browser and Node.js.
- Secure: Uses
crypto.getRandomValues()in the browser andcrypto.randomUUID()orcrypto.randomBytes()in Node.js for high-quality randomness. - Collision-Resistant: Provides 122 bits of randomness, making collisions practically impossible for most applications.
API
ts
function uuid(): string;Returns
- A string representing a randomly generated UUID v4 (e.g.,
'f47ac10b-58cc-4372-a567-0e02b2c3d479').
Examples
Generating a Unique ID
ts
import { uuid } from '@vielzeug/toolkit';
const userId = uuid();
const orderId = uuid();
console.log('User ID:', userId);
console.log('Order ID:', orderId);Usage in Objects
ts
import { uuid } from '@vielzeug/toolkit';
const items = [
{ id: uuid(), name: 'Item 1' },
{ id: uuid(), name: 'Item 2' },
];Implementation Notes
- The function ensures that the version bit is set to
4and the variant bit is set to10xx(as per the RFC 4122 spec). - In environments where a cryptographically secure RNG is not available (though rare in modern environments), it may fall back to
Math.random(), but this is not recommended for security-sensitive applications.