Install ulid via npm
masterTo use the ulid library in your project, install it using npm:
npm install ulid --saverepository·master·Indexed 25 days ago
https://github.com/ulid/javascriptA JavaScript implementation of Universally Unique Lexicographically Sortable Identifiers (ULID). Version 3.0.2 provides 128-bit compatible, URL-safe, and sortable 26-character identifiers. Features include monotonic generation via monotonicFactory, ULID validation with isValid, timestamp encoding/decoding, and conversion utilities between ULID and UUID.
To use the ulid library in your project, install it using npm:
npm install ulid --saveImport the ulid function to generate a new, unique, lexicographically sortable 26-character identifier.
import { ulid } from "ulid";
ulid(); // "01ARZ3NDEKTSV4RRFFQ69G5FAV"You can pass a millisecond timestamp as an argument to ulid(). This ensures the time component of the generated ULID remains consistent, which is useful for data migrations.
ulid(1469918176385) // "01ARYZ6S41TSV4RRFFQ69G5FAV"By default, ulid uses cryptographically-secure PRNGs (crypto.getRandomValues in browsers or crypto.randomBytes in Node.js). If you need to use an insecure generator like Math.random, you can pass it to monotonicFactory.
const ulid = monotonicFactory(() => Math.random());
ulid(); // "01BXAVRG61YJ5YSBRM51702F6M"Use the isValid function to check if a given string is a valid ULID.
import { isValid } from "ulid";
isValid("01ARYZ6S41TSV4RRFFQ69G5FAV"); // true
isValid("01ARYZ6S41TSV4RRFFQ69G5FA"); // falseTo ensure that ULIDs generated within the same millisecond maintain a strict sort order, use monotonicFactory. This increments the least-significant random bits for subsequent calls within the same timestamp, and preserves sort order even if a lower timestamp is provided later.
import { monotonicFactory } from "ulid";
const ulid = monotonicFactory();
// Strict ordering for the same timestamp
ulid(150000); // "000XAL6S41ACTAV9WEVGEMMVR8"
ulid(150000); // "000XAL6S41ACTAV9WEVGEMMVR9"
// Preserves sort order even with a lower timestamp
ulid(100000); // "000XAL6S41ACTAV9WEVGEMMVRD"You can extract the timestamp from a ULID using decodeTime, or create a ULID time component string using encodeTime.
Note: encodeTime only encodes the time portion (the first 10 characters) of a ULID, not a full 26-character ID.
ulid from the command line via npx or by installing it globally. Use the --count flag to generate multiple IDs at once.isValid(ulid) to check if a given string is a valid ULID.ULIDError. You can check the specific error type using the ULIDErrorCode enum.decodeTime(ulid) or convert a timestamp back into a ULID component using encodeTime(time).ulid() function to generate a new Universally Unique Lexicographically Sortable Identifier. This is the primary way to create a new ULID string.