CUID2 in JavaScript and TypeScript
Generate IDs, enforce your schema, and check the results locally.
Review notes,
The downloadable Node.js example is executed against @paralleldrive/cuid2@3.3.0.
Twelve assertions check output lengths, constructed strings, and an application length rule. These are functional checks, not a randomness audit or collision benchmark.
Install and generate
npm install --save-exact @paralleldrive/cuid2@3.3.0Use an ES module with Node.js 22 or later. Keep the default length unless your collision analysis supports a shorter one.
import { createId, init, isCuid } from '@paralleldrive/cuid2';
const id = createId();
console.log(id.length); // 24
console.log(isCuid(id)); // true
const createShortId = init({ length: 10 });
console.log(createShortId().length); // 10Validate your application's format
The package accepts lengths from 2 to 32. It checks shape, not randomness or origin:
| Input | isCuid() | Meaning |
|---|---|---|
'ab' | true | Not restricted to 24 characters. |
'a'.repeat(24) | true | Constructed strings pass too. |
'cjld2cjxh0000qzrmn831i7rn' | true | Legacy CUID v1 also fits. |
'1abc', 'AB', 'a'.repeat(33) | false | Wrong prefix, case, or length. |
import { isCuid } from '@paralleldrive/cuid2';
const isProjectId = (value) =>
typeof value === 'string' && value.length === 24 && isCuid(value);Keep migration rules for existing 25-character IDs. Check record existence and permissions separately; a passing format check grants no access.
Run the checks yourself
Download cuid2-check.mjs into the directory where you installed the package, then run node cuid2-check.mjs. The 12 assertions stop on any unexpected result.
Expected output: “All 12 checks passed. Format is not proof of origin or uniqueness.”
Enforce uniqueness in storage
CREATE TABLE project (
id varchar(24) PRIMARY KEY,
name text NOT NULL
);Handle duplicate-key errors in your insert path. Decide whether the operation is a retry, an input bug, or needs a new candidate ID.
Working with legacy IDs?
CUID v1 is deprecated. Preserve existing IDs and references when changing generators; follow the migration guide.
Sources: CUID2 public API, changelog, and legacy CUID.