Generate CUIDs in Javascript

Resources  |  Generate CUIDs in Javascript

Generating a CUID (Collision-resistant Unique Identifier) in JavaScript involves using various techniques to ensure uniqueness, such as the current timestamp, a counter, a machine fingerprint, and randomness. Below is an example implementation of generating a CUID in JavaScript.

Steps to Generate a CUID in JavaScript

  1. Timestamp: Get the current timestamp in milliseconds.
  2. Counter: Use a counter to handle multiple CUIDs generated in a short period.
  3. Fingerprint: Generate a machine-specific fingerprint.
  4. Randomness: Add random characters to further reduce the risk of collisions.
  5. Base36 Encoding: Encode the components using Base36 for readability.

Example Code

const base36Chars = '0123456789abcdefghijklmnopqrstuvwxyz';
let counter = 0;
let lastTimestamp = 0;

function encodeBase36(value) {
    let result = '';
    while (value > 0) {
        result = base36Chars[value % 36] + result;
        value = Math.floor(value / 36);
    }
    return result;
}

function getMachineFingerprint() {
    const crypto = require('crypto');
    const os = require('os');
    const hostname = os.hostname();
    const hash = crypto.createHash('md5').update(hostname).digest('hex');
    return hash.slice(0, 4);
}

function getRandomString(length) {
    let result = '';
    for (let i = 0; i < length; i++) {
        result += base36Chars[Math.floor(Math.random() * 36)];
    }
    return result;
}

function generateCUID() {
    const timestamp = Date.now();

    if (timestamp === lastTimestamp) {
        counter++;
    } else {
        lastTimestamp = timestamp;
        counter = 0;
    }

    const timestampBase36 = encodeBase36(timestamp);
    const counterBase36 = encodeBase36(counter);
    const fingerprint = getMachineFingerprint();
    const randomString = getRandomString(4);

    return `c${timestampBase36}${counterBase36}${fingerprint}${randomString}`;
}

console.log(generateCUID());

Explanation

  1. Base36 Encoding:

    • The encodeBase36 function converts a number to a Base36 encoded string.
  2. Timestamp:

    • const timestamp = Date.now(); gets the current timestamp in milliseconds.
  3. Counter:

    • The counter is used to handle multiple CUIDs generated within the same millisecond. The counter is incremented and reset as needed.
  4. Machine Fingerprint:

    • getMachineFingerprint generates a fingerprint using the MD5 hash of the machine's hostname.
  5. Random String:

    • getRandomString generates a random string of specified length using Base36 characters.
  6. Combine Components:

    • The generateCUID function combines the timestamp, counter, fingerprint, and random parts to form the final CUID.

Summary

This JavaScript implementation of CUID generation uses available functions and libraries to handle timestamps, hashing, randomness, and counters. This approach ensures that the generated CUIDs are unique, readable, and collision-resistant, making them suitable for various applications.