createId()
Create a generator with fixed options — set the size, separator, or alphabet once and reuse it.
Signature
ts
function createId(options?: {
size?: number; // default: 24
separator?: string; // default: "_"
alphabet?: string; // default: base62 (0-9A-Za-z)
}): <P extends string>(prefix: P) => `${P}_${string}`Options
| Option | Type | Default | Description |
|---|---|---|---|
| size | number | 24 | Number of random characters (1–4096). |
| separator | string | "_" | Text between the prefix and the random part. |
| alphabet | string | base62 | Characters used for the random part. |
Custom size
import { createId } from "prefid";
const id = createId({ size: 16 });
id("user"); // => "user_a1b2c3d4e5f6g7h8"
id("order"); // => "order_9f8e7d6c5b4a3F2e"const { createId } = require("prefid");
const id = createId({ size: 16 });
id("user"); // => "user_a1b2c3d4e5f6g7h8"
id("order"); // => "order_9f8e7d6c5b4a3F2e"Custom separator
ts
const id = createId({ separator: "-" });
id("user"); // => "user-a1b2c3d4e5f6g7h8i9j0k1l2"Custom alphabet
Provide your own alphabet — for example, a lowercase set that omits look-alike characters for human-friendly codes.
ts
// Lowercase, unambiguous alphabet (no 0/O/1/l)
const id = createId({ alphabet: "23456789abcdefghjkmnpqrstuvwxyz" });
id("code"); // => "code_mn7pqr2stuv9wxyz34abcdef"For a ready-made unambiguous, case-insensitive alphabet, import the BASE32_CROCKFORD preset — the same alphabet ULID uses. It drops the ambiguous letters I, L, O, and U, so ids are safe to read aloud, print, or store in case-folding systems.
import { createId, BASE32_CROCKFORD } from "prefid";
// Crockford Base32 (the ULID alphabet): omits I, L, O, U.
const id = createId({ alphabet: BASE32_CROCKFORD });
id("code"); // => "code_MN7PQR2STVWXYZ34ABCDEFGH" — no 0/O or 1/l confusion"const { createId, BASE32_CROCKFORD } = require("prefid");
// Crockford Base32 (the ULID alphabet): omits I, L, O, U.
const id = createId({ alphabet: BASE32_CROCKFORD });
id("code"); // => "code_MN7PQR2STVWXYZ34ABCDEFGH" — no 0/O or 1/l confusion"Notes
sizemust be an integer between 1 and 4096, andalphabetmust contain at least 2 characters — otherwisecreateIdthrows aRangeError. The upper bound guards against a hugesizeexhausting memory when the value comes from untrusted input.- A larger
sizeoralphabetmeans more entropy and even lower collision odds.