ToolDeck

CUID জেনারেটর

কোলিশন-রেসিস্ট্যান্ট ইউনিক ID তৈরি করুন (CUID v1)

সংখ্যা

তৈরি করা CUID

CUID তৈরি করতে জেনারেট বাটনে ক্লিক করুন

CUID v1 লেগ্যাসি ফরম্যাট। নতুন প্রজেক্টে CUID2 ব্যবহার করুন।

What is CUID?

CUID (Collision-Resistant Unique Identifier) is an open-source algorithm for generating unique IDs that work well in distributed systems without a central coordinator. Unlike a simple UUID, a CUID is designed to be horizontally scalable — multiple servers or browser tabs can each generate IDs independently with minimal risk of collision.

Every CUID starts with the lowercase letter c, making the format immediately recognisable at a glance. The remaining characters are all lowercase alphanumeric (base36), so a CUID is URL-safe and can be used directly as a URL path segment or database primary key without additional encoding.

The original CUID specification (v1) was created by Eric Elliott and popularised via the cuid npm package. It is now superseded by CUID v2, which provides cryptographic security. This page — and the generator above — produces CUID v1 IDs, the classic format still widely encountered in production codebases.

CUID Structure

A CUID v1 is roughly 25 characters long and is composed of five concatenated segments, each carrying a different type of entropy:

Example: clrc4gkwz001ag2hs3k7f9m2q
cprefixAlways the letter "c" — marks a CUID
lrc4gkwztimestampMillisecond timestamp in base36 (~8 chars)
001acounter4-char base36 counter — prevents same-millisecond collisions
g2hsfingerprint4-char base36 host fingerprint (browser/env info)
3k7f9m2qrandom8-char base36 random block — two 32-bit values

The segments are simply concatenated — there are no separators. The total length varies slightly depending on the current timestamp value but stays at approximately 25 characters.

How CUID Prevents Collisions

Collision resistance comes from layering independent sources of entropy so that even in worst-case scenarios (thousands of IDs generated per millisecond across many machines) the probability of two identical IDs remains vanishingly small.

Millisecond Timestamp
The first segment encodes the current time in base36. IDs generated at different moments automatically sort lexicographically by creation time — useful for pagination and debugging.
Monotonic Counter
Within the same process, the 4-char counter increments with every generated ID. Even if two calls happen in the same millisecond on the same machine, the counter guarantees uniqueness for up to 65,536 IDs per millisecond.
Machine Fingerprint
A hash derived from environment-specific data (process ID + hostname in Node.js; screen dimensions + navigator info in the browser). This differentiates IDs generated on separate hosts at the exact same millisecond with the same counter value.
Random Block
The final 8 characters come from two independent 32-bit random values encoded in base36. This adds a final layer of entropy that protects against collisions even if the fingerprint of two machines happens to hash to the same value.

CUID vs UUID v4

Both CUID and UUID v4 are widely used for client-side ID generation. They take different approaches to the same problem:

FeatureCUID v1UUID v4
Formatc + base36 (~25 chars)hex groups (36 chars with dashes)
SortableRoughly (timestamp prefix)No
URL-safeYes (alphanumeric only)Mostly (dashes are fine in URLs)
Collision resistanceHigh — timestamp + counter + fingerprint + randomHigh — 122 bits of random
PredictabilityPartially (timestamp visible)None (pure random)
Length~25 characters36 characters
Requires coordinationNoNo

UUID v4 is the safer choice for security-sensitive scenarios because it reveals no timing information. CUID has the edge when you want IDs that are vaguely sortable, shorter, and free of hyphens — handy for use in URLs, filenames, or logs where you want to quickly identify when a record was created.

CUID v1 vs CUID2

The CUID specification has been revised significantly. Understanding the differences helps you pick the right version for your project:

AspectCUID v1CUID v2
AlgorithmDeterministic componentsSHA-3 based, fully opaque
CryptographicNoYes
Timestamp visibleYesNo
FormatStarts with "c"Starts with "c" (configurable)
npm package@paralleldrive/cuid (deprecated)@paralleldrive/cuid2
Length~25 chars24 chars (default, configurable)

For new projects, CUID v2 is the recommended choice. Its SHA-3 based construction means the output is opaque — no timestamp, counter, or fingerprint can be reverse-engineered from the ID. Use CUID v1 only when you need backward compatibility with an existing dataset or want a dependency-free implementation.

Use Cases

Distributed Databases
Multiple database shards or microservices can each generate primary keys independently without a sequence table or central ID service, eliminating a single point of failure.
Client-Side ID Generation
A browser can assign a CUID to a new record before sending it to the server, enabling optimistic UI updates and eliminating the round-trip needed to fetch a server-assigned ID.
Offline-First Apps
Mobile or PWA apps that operate without connectivity can create records with stable IDs that survive sync — no conflicts when the device comes back online.
URL Slugs
CUIDs contain only alphanumeric characters, making them safe to embed directly in URL paths without percent-encoding. The timestamp prefix adds a rough creation-time ordering.
Event / Log Correlation
Because the timestamp is encoded in the first segment, log entries tagged with CUIDs can be roughly sorted by creation time even across distributed log aggregators.
ORM / Prisma Default
Prisma uses CUID as its default @id strategy for String primary keys — @default(cuid()) — making it one of the most widely deployed ID formats in the JavaScript ecosystem.

Code Examples

Install the official CUID v2 package (recommended) or write a minimal v1 implementation with no dependencies:

JavaScript / TypeScript
// npm install @paralleldrive/cuid2  (recommended — CUID v2)
import { createId } from '@paralleldrive/cuid2'

const id = createId()
// → 'tz4a98xxat96iws9zmbrgj3a'

// Custom length
import { init } from '@paralleldrive/cuid2'
const createShortId = init({ length: 10 })
createShortId() // → 'zxp1l6mf4c'

If you prefer a dependency-free Node.js implementation of the v1 algorithm:

Node.js (no dependencies)
// Pure Node.js — CUID v1 style (no dependencies)
let counter = 0

function pad(str, size) {
  return str.padStart(size, '0').slice(-size)
}

function fingerprint() {
  const os = require('os')
  const source = [process.pid, os.hostname().length].join('')
  let hash = 0
  for (const c of source) {
    hash = ((hash << 5) - hash) + c.charCodeAt(0)
    hash |= 0
  }
  return pad(Math.abs(hash).toString(36), 4)
}

function cuid() {
  const timestamp = Date.now().toString(36)
  const cnt       = pad((counter++ & 0xffff).toString(36), 4)
  const fp        = fingerprint()
  const rnd       = pad(Math.floor(Math.random() * 0xffffffff).toString(36), 4)
              + pad(Math.floor(Math.random() * 0xffffffff).toString(36), 4)
  return 'c' + timestamp + cnt + fp + rnd
}

console.log(cuid()) // → 'clrc4gkwz001ag2hs3k7f9m2q'

Using CUID as a database primary key with Prisma and PostgreSQL:

Prisma / SQL
-- Use CUID as a primary key in PostgreSQL
CREATE TABLE users (
  id   TEXT        PRIMARY KEY DEFAULT gen_cuid(),
  name TEXT        NOT NULL,
  created_at TIMESTAMPTZ DEFAULT now()
);

-- Prisma schema (auto-generates CUID by default)
model User {
  id        String   @id @default(cuid())
  name      String
  createdAt DateTime @default(now())
}

Frequently Asked Questions

Is CUID URL-safe?
Yes. CUID v1 uses only lowercase letters and digits (base36 encoding), which are all URL-safe characters. No percent-encoding is needed when using a CUID in a URL path or query parameter.
Is CUID cryptographically secure?
No. CUID v1 uses Math.random() and exposes a visible timestamp prefix. It is not suitable for security-sensitive purposes such as session tokens or password-reset links. For those use cases, use crypto.randomUUID() or CUID v2.
CUID vs NanoID — which should I choose?
NanoID is cryptographically secure, shorter (21 chars by default), and uses a customisable alphabet. Choose NanoID when security matters or when you need a shorter ID. Choose CUID when you want a roughly-sortable, timestamp-prefixed ID that is human-debuggable.
Should I use CUID v1 or CUID v2?
CUID v2 is the current recommendation. It is cryptographically secure, does not leak timing information, and is actively maintained. CUID v1 is useful when you need a simple dependency-free implementation or are maintaining a legacy system. This generator produces CUID v1 IDs.
CUID vs ULID — what is the difference?
Both are timestamp-prefixed and lexicographically sortable. ULID uses Crockford base32 (128 bits total, 48-bit timestamp + 80-bit random), making it slightly more random. CUID adds a machine fingerprint and a monotonic counter, which improves collision resistance on the same host within the same millisecond. ULID sorts more reliably because the timestamp occupies the full high-order portion.
Is CUID guaranteed to be unique?
No ID scheme can give a mathematical guarantee without a central coordinator. CUID makes collisions extremely unlikely by combining four independent entropy sources: the timestamp, a per-process counter, a machine fingerprint, and random data. In practice, collisions are far less likely than hardware failure.

সম্পর্কিত টুলস