When generating ULIDs within the same millisecond, the random component is incremented to ensure strict monotonicity. If more than 2^80 ULIDs are generated within the same millisecond, generation will fail.
interface UlidOptions { /** * The time to use for generating the ULID. */ time?: Date; /** * The random bytes to use for generating the ULID. * Must be exactly 10 bytes. */ random?: Uint8Array;}
You’re working with systems that expect standard UUIDs
Sorting by creation time is not important
Case-insensitive identifiers are preferred
import { generateUuid4 } from "@temelj/id";// User IDs that don't need orderingconst userId = generateUuid4();// Primary keys in relational databasesconst recordId = generateUuid4();
Use ULID when:
You need lexicographically sortable IDs
Timestamp information is valuable
Shorter string representation is preferred
You want to maintain insertion order
import { generateUlid } from "@temelj/id";// Event IDs that should be sortable by timeconst eventId = generateUlid();// Log entriesconst logId = generateUlid();// Time-series dataconst dataPointId = generateUlid();
import { generateUlid } from "@temelj/id";interface Event { id: string; type: string; timestamp: Date; data: any;}function createEvent(type: string, data: any): Event { const now = new Date(); return { id: generateUlid({ time: now }), type, timestamp: now, data };}const events = [ createEvent('user.login', { userId: '123' }), createEvent('user.logout', { userId: '123' })];// Events are naturally sorted by their IDevents.sort((a, b) => a.id.localeCompare(b.id));
import { generateUlidList } from "@temelj/id";// Generate multiple IDs efficientlyconst orderIds = generateUlidList(100);// All IDs are monotonically increasingconsole.log(orderIds[0] < orderIds[1]); // trueconsole.log(orderIds[98] < orderIds[99]); // true// Use for bulk insert operationsconst orders = orderIds.map((id, index) => ({ id, orderNumber: index + 1, status: 'pending'}));
import { isUuid4Valid, isUlidValid } from "@temelj/id";function validateId(id: string, type: 'uuid' | 'ulid'): boolean { if (type === 'uuid') { return isUuid4Valid(id); } return isUlidValid(id);}// API route handlerfunction getUserById(id: string) { if (!isUuid4Valid(id)) { throw new Error('Invalid user ID format'); } // Fetch user...}
For new projects, consider using ULIDs for primary keys if you benefit from time-based sorting. For compatibility with existing systems or maximum randomness, use UUID v4.