Custom ID Generator
A utility to generate unique IDs similar to CUIDs
createId generates compact, URL-safe identifiers with entropy from the current time, a counter, a runtime fingerprint, and random salt.
It is intended for application identifiers where you want a short generated string without depending on a separate ID package.
Installation
CLI
npx shadcn add https://ui.tiesen.id.vn/r/create-id.jsonManual
Copy and paste the following code into your project.
import { createHash } from 'node:crypto'const createRandom = () => { if ( typeof globalThis !== 'undefined' && typeof globalThis.crypto.getRandomValues === 'function' ) { return () => { const buffer = new Uint32Array(1) globalThis.crypto.getRandomValues(buffer) return (buffer.at(0) ?? 0) / 0x1_00_00_00_00 } } return Math.random}const random = createRandom()const createEntropy = (length = 4, rand = random) => { let entropy = '' while (entropy.length < length) entropy += Math.floor(rand() * 36).toString(36) return entropy}const bufToBigInt = (buf: Buffer) => { let v = 0n // oxlint-disable-next-line no-bitwise for (const i of buf) v = (v << 8n) + BigInt(i) return v}const hash = (input: string) => { const hashBuf = createHash('sha3-512').update(input).digest() return bufToBigInt(hashBuf).toString(36).slice(1)}const createFingerprint = ({ globalObj = globalThis, random: rand = random,}) => { const globals = Object.keys(globalObj).toString() const sourceString = globals.length > 0 ? globals + createEntropy(32, rand) : createEntropy(32, rand) return hash(sourceString).slice(0, 32)}// oxlint-disable-next-line no-param-reassign, no-plusplusconst createCounter = (count: number) => () => count++export function createId(rand = random): string { const time = Date.now().toString(36) const count = createCounter(Math.floor(rand() * 476_782_367))().toString(36) const fingerprint = createFingerprint({ random: rand }) const salt = createEntropy(24, rand) const hashInput = `${time}${salt}${count}${fingerprint}` return `c${hash(hashInput).slice(1, 24)}`}Usage
import { createId } from '@/lib/create-id'
const id = createId()
console.log(id)
// Example: c8f0g3...The generated identifier always starts with c and is derived from multiple changing inputs rather than a single random call.
Randomness
The generator uses crypto.getRandomValues when the runtime exposes it and falls back to Math.random when it does not.
You can pass a custom random function for deterministic tests:
const id = createId(() => 0.5)A deterministic random function is useful only for tests; do not use one for production IDs.
API Reference
createId
function createId(rand?: () => number): string| Parameter | Description |
|---|---|
rand | Optional random source used by the generator. Defaults to the best available runtime random source. |
The current implementation combines a base-36 timestamp, counter entropy, runtime fingerprint, and additional random salt before hashing with SHA3-512.