ToolDeck

CUID2 জেনারেটর

নিরাপদ পরবর্তী প্রজন্মের CUID2 আইডেন্টিফায়ার তৈরি করুন

সংখ্যা
দৈর্ঘ্য

তৈরি করা CUID2

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

What is CUID2?

CUID2 (Collision-resistant Unique ID, version 2) is the next-generation successor to CUID v1, designed to generate short, cryptographically secure, opaque IDs that are safe to use as primary keys in databases, URLs, and distributed systems.

Unlike its predecessor, CUID2 reveals no information about the time of creation, the host machine, or the process that generated it. Every ID is a seemingly random string that starts with a random lowercase letter followed by a base-36 hash derived from SHA-512. The default length is 24 characters, but you can configure it anywhere from 2 to 32 characters to suit your storage constraints.

CUID2 is widely recommended by modern database toolkits. Prisma adopted it as the default ID strategy for its @default(cuid()) scalar, and PlanetScale, Neon, and other serverless database providers explicitly list CUID2 as a preferred ID format because it avoids the sequential-scan vulnerabilities of auto-increment integers while being shorter and more readable than a UUID.

Why CUID2 Replaced CUID v1

CUID v1, released in 2012 by Eric Elliott, was a major improvement over plain UUIDs for client-side ID generation. However, security researchers discovered two fundamental problems with its design:

  • Fingerprinting: The host fingerprint embedded in every CUID v1 value could be used to identify the machine or process that generated the ID, leaking operational metadata to anyone who could observe the IDs.
  • Predictability: Because CUID v1 incorporated a monotonically increasing counter and a timestamp segment, an attacker who observed several IDs could predict the approximate range of future IDs, enabling enumeration attacks against APIs that use IDs as the sole authorization check.
  • Non-cryptographic hash: CUID v1 used a simple non-cryptographic hashing step that did not meet modern security standards.

Eric Elliott, the original author, formally deprecated CUID v1 and authored CUID2 from scratch to address all of these issues. The new algorithm uses the Web Crypto API (SHA-512) and eliminates all deterministic components, making each ID statistically independent of every other.

CUID2 Design Principles

Unpredictable
No timestamp, counter, or host fingerprint is embedded. Each ID is generated from a fresh cryptographic random salt combined with SHA-512.
Flat distribution
Base-36 encoding of the SHA-512 digest produces near-uniform character distribution, reducing indexing hotspots in B-tree databases.
URL-safe by default
The alphabet is restricted to lowercase a–z and digits 0–9 — no hyphens, underscores, or mixed case — making IDs safe in URLs without percent-encoding.
Configurable length
You choose the length (2–32). Shorter IDs mean higher collision probability; the recommended default of 24 gives ~4 × 10³⁷ unique values.
Always starts with a letter
The first character is always a random lowercase letter, ensuring CUID2 values are valid HTML element IDs and CSS selectors without escaping.
No server required
CUID2 relies solely on the Web Crypto API available in all modern browsers and Node.js 15+, so IDs can be generated on the client with the same security guarantees as the server.

CUID2 vs CUID v1 — Comparison

The table below summarises the key differences between CUID2 and the now-deprecated CUID v1. If you are currently using CUID v1, migrating to CUID2 is strongly recommended.

AttributeCUID2CUID v1
SecurityCryptographic (SHA-512)Non-cryptographic (fingerprint-based)
PredictabilityOpaque — no leaked metadataTimestamp + fingerprint visible in ID
LengthConfigurable (2–32 chars)Fixed 25 chars
PrefixRandom a–z letterAlways starts with "c"
DistributionFlat / uniformMonotonically increasing segments
StatusActively maintainedDeprecated by original author

CUID2 vs UUID v4 — Comparison

UUID v4 is the dominant standard for random unique IDs. CUID2 offers several practical advantages over UUID v4 without sacrificing security.

AttributeCUID2UUID v4
Default length24 characters36 characters (with hyphens)
URL-safeYes — lowercase a–z + 0–9Requires encoding (contains hyphens)
Custom lengthYes (2–32)No — always 128 bits / 36 chars
SortableNo (by design)No (v4 is random)
Entropy sourceSHA-512 + Web CryptoCSPRNG
Character setBase-36 (a–z, 0–9)Hex + hyphens

The main trade-off is familiarity: UUID v4 is an IETF standard (RFC 4122) recognised by virtually every database, programming language, and API framework out of the box. CUID2 is a community standard with growing but not universal support. Choose UUID v4 when interoperability with external systems is paramount; choose CUID2 when you control both ends and prefer shorter, URL-safe IDs.

Who Uses CUID2

CUID2 has seen rapid adoption across the modern JavaScript and TypeScript ecosystem:

  • Prisma — the most popular TypeScript ORM uses CUID2 as the recommended default for @id fields with @default(cuid()) in Prisma Schema v2+.
  • PlanetScale — their documentation and starter templates recommend CUID2 for application-generated primary keys to avoid sequential scan performance issues on their distributed MySQL platform.
  • Drizzle ORM — provides a built-in cuid2() default helper for column definitions.
  • tRPC boilerplates — many community tRPC + Prisma starter templates ship with CUID2 as the primary key strategy.
  • T3 Stack — the create-t3-app scaffolding tool uses Prisma with CUID2 defaults in generated schema files.

Code Examples

The official @paralleldrive/cuid2 npm package provides a simple API:

JavaScript (npm — @paralleldrive/cuid2)
import { createId } from '@paralleldrive/cuid2'

// Generate a single CUID2 (default length: 24)
const id = createId()
console.log(id) // e.g. "tz4a98xxat96iws9zmbrgj3a"

// Custom length
import { init } from '@paralleldrive/cuid2'
const createShortId = init({ length: 16 })
const shortId = createShortId()
console.log(shortId) // e.g. "tz4a98xxat96iws9"

Using CUID2 with Prisma schema:

Prisma Schema
model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

Generating CUID2 in Node.js without the npm package (using only Web Crypto API, as this tool does in the browser):

Node.js (Web Crypto — no dependencies)
async function generateCuid2(length = 24) {
  const alphabet = 'abcdefghijklmnopqrstuvwxyz'

  // Random prefix letter
  const firstByte = crypto.getRandomValues(new Uint8Array(1))[0]
  const firstChar = alphabet[firstByte % 26]

  // Random 32-byte salt
  const salt = crypto.getRandomValues(new Uint8Array(32))
  const saltHex = [...salt].map(b => b.toString(16).padStart(2, '0')).join('')

  // SHA-512 of timestamp + salt
  const input = Date.now().toString(36) + saltHex
  const hashBuffer = await crypto.subtle.digest(
    'SHA-512',
    new TextEncoder().encode(input)
  )

  // Encode hash bytes as base-36 string
  const bytes = new Uint8Array(hashBuffer)
  let hash = ''
  for (let i = 0; i < bytes.length; i += 8) {
    let chunk = 0n
    for (let j = 0; j < 8 && i + j < bytes.length; j++) {
      chunk = (chunk << 8n) | BigInt(bytes[i + j])
    }
    hash += chunk.toString(36)
  }

  return (firstChar + hash).slice(0, length)
}

// Usage
const id = await generateCuid2()
console.log(id) // e.g. "m7k3r9p2nxq8zt5a6cwj4bvd"

Frequently Asked Questions

Is CUID2 backward compatible with CUID v1?
No. CUID2 IDs look completely different from CUID v1 IDs. CUID v1 always starts with the letter "c" and has a fixed 25-character length. CUID2 starts with a random letter and has a configurable length (default 24). If you migrate an existing database, you will need to handle both formats or run a migration to replace all CUID v1 values.
What length should I use?
The default of 24 characters is the recommended choice for most applications. It provides approximately 4 × 10³⁷ unique values, making collisions statistically impossible even at massive scale. Use 16 characters if storage is critical and your dataset is under a few billion records. Use 32 characters for the maximum security margin.
Is CUID2 sortable by creation time?
No — and this is intentional. CUID2 deliberately discards all temporal information to prevent enumeration attacks and fingerprinting. If you need time-ordered IDs, consider ULID or UUID v7 instead. CUID2 trades sortability for security and opacity.
CUID2 vs NanoID — which should I choose?
Both are secure and URL-safe. NanoID is slightly shorter at 21 characters by default and uses a larger alphabet (A–Za–z0–9_-) giving more entropy per character. CUID2 uses a restricted alphabet (a–z, 0–9) that is safer in CSS selectors and always starts with a letter. Choose NanoID if you want maximum entropy density; choose CUID2 if Prisma/ORM integration or CSS-safe IDs are important.
Is CUID2 URL-safe?
Yes. CUID2 only uses lowercase letters (a–z) and digits (0–9). It contains no hyphens, underscores, plus signs, slashes, or equals signs, so it can be embedded directly in URLs, HTML id attributes, CSS selectors, and file names without any encoding.
Can I use CUID2 as a database primary key?
Yes, and it is one of the primary use cases. CUID2 avoids the sequential pattern of auto-increment integers (which can leak row counts and enable enumeration), is shorter than a UUID (saving index space), and is URL-safe. Most databases store it as a VARCHAR(24) or TEXT column. Note that unlike ULIDs or UUID v7, CUID2 values are not time-ordered, so if your queries rely heavily on insertion-order scans you may prefer a sortable alternative.