node-comfortv2.0.0

nc.id

Unique ids: UUID v4 and v7, ULID, nanoid-style ids, Snowflakes, tokens and short codes. All of them use the secure random generator of node:crypto, with no bias.

const { id } = require("@ix-xs/node-comfort");
import { uuid } from "@ix-xs/node-comfort/id";
id.uuidv7();  // "0190a5c4-7c1e-7b2a-9f3e-1c2d3e4f5a6b", sorts by creation time
id.nano();    // "V1StGXR8_Z5jdHi6B-myT"
id.code();    // "K7QF9X"
id.token(32); // for API keys and reset links
GuideExplanations and examples for nc.id.
Read the guide →

Functions

nc.id.uuid()

uuid(): string

A random UUID (version 4). For ids that sort by date, see uuidv7().

Returns string

Example

id.uuid(); // "3f2504e0-4f89-41d3-9a0c-0305e82c3301"

nc.id.uuidv7()

uuidv7(): string

A UUID v7: it starts with a timestamp, so ids sort by creation time. That keeps database indexes compact, which makes them great primary keys. Ids from the same process always increase, even within a millisecond.

Returns string

Example

id.uuidv7();               // "0190a5c4-7c1e-7b2a-9f3e-1c2d3e4f5a6b"
id.timestamp(id.uuidv7()); // when it was created

nc.id.ulid()

ulid(time?: number): string

A ULID: 26 URL-safe characters that sort by creation time. Ids made in the same millisecond still increase.

Parameters

NameTypeDescription
timeoptionalnumberTimestamp to encode, in ms. Defaults to now.

Returns string

Example

id.ulid();                       // "01HQ3Z8K9V3N5W7Y2XJ4T6R8PB"
id.ulid(Date.UTC(2024, 0, 1));   // for a given time

nc.id.nano()

nano(size?: number, alphabet?: string): string

A short, URL-safe random id, like nanoid. At 21 characters, collisions are as unlikely as with a UUID.

Parameters

NameTypeDescription
sizeoptionalnumberDefault: 21
alphabetoptionalstring2 to 256 characters. Defaults to letters, digits, _ and -.

Returns string

Example

id.nano();                      // "V1StGXR8_Z5jdHi6B-myT"
id.nano(10);                    // "IRFa-VaY2b"
id.nano(8, "0123456789abcdef"); // "4f90d13a"

nc.id.customAlphabet()

customAlphabet(alphabet: string, size?: number): (size?: number) => string

Makes an id generator with your own alphabet and length.

Parameters

NameTypeDescription
alphabetstring
sizeoptionalnumberDefault: 21

Returns (size?: number) => string

Example

const orderId = id.customAlphabet("0123456789ABCDEF", 12);
orderId(); // "4F1A09C2BB7E"

nc.id.token()

token(bytes?: number, encoding?: TokenEncoding): string

A random token for API keys, session ids, reset links...

Parameters

NameTypeDescription
bytesoptionalnumberHow much randomness, in bytes.Default: 32
encodingoptionalTokenEncodingDefault: "hex"

Returns string

Example

id.token();                // 64 hex characters
id.token(16, "base64url"); // 22 URL-safe characters
id.token(16, "base58");    // no look-alike characters

nc.id.code()

code(length?: number, alphabet?: string): string

A short code that's easy to read aloud and type: no 0/O or 1/I/L mix-ups. For invites, coupons and verification codes.

Parameters

NameTypeDescription
lengthoptionalnumberDefault: 6
alphabetoptionalstringDefault: "ABCDEFGHJKMNPQRSTUVWXYZ23456789"

Returns string

Example

id.code();                // "K7QF9X"
id.code(4, "0123456789"); // "3920"

nc.id.snowflake()

snowflake(options?: SnowflakeOptions): string

A Snowflake id, the 64-bit format used by Discord and Twitter. Returned as a string because it doesn't fit in a JavaScript number.

Parameters

NameType
optionsoptionalSnowflakeOptions

Returns string

Example

id.snowflake(); // "1215361932810932224"

nc.id.parseSnowflake()

parseSnowflake(id: string | bigint, options?: SnowflakeOptions): ParsedSnowflake

Decodes a Snowflake. With the default epoch, it reads Discord ids.

Parameters

NameTypeDescription
idstring | bigint
optionsoptionalSnowflakeOptionsUse the epoch it was created with.

Returns ParsedSnowflake

Example

id.parseSnowflake("175928847299117063").date; // 2016-04-30T11:18:25.796Z

nc.id.timestamp()

timestamp(value: string): Date | undefined

When a ULID or a UUID v7 was created.

Parameters

NameType
valuestring

Returns Date | undefined

Example

id.timestamp(id.ulid()); // now
id.timestamp(id.uuid()); // undefined, v4 has no time in it

nc.id.seq()

seq(prefix?: string): string

Readable sequential ids like "user-1", "user-2", counted per prefix. Only unique within the current process; handy in logs and tests.

Parameters

NameTypeDescription
prefixoptionalstringDefault: ""

Returns string

Example

id.seq("user"); // "user-1"
id.seq("user"); // "user-2"

nc.id.hash()deprecated

Use nc.crypto.hash(). This alias goes away in 3.0.

hash(value: string | Buffer<ArrayBufferLike> | Uint8Array<ArrayBufferLike>, options?: HashOptions): string

Hashes a value.

Parameters

NameType
valuestring | Buffer | Uint8Array
optionsoptionalHashOptions

Returns string

nc.id.hmac()deprecated

Use nc.crypto.hmac(). This alias goes away in 3.0.

hmac(value: string | Buffer<ArrayBufferLike> | Uint8Array<ArrayBufferLike>, secret: string | Buffer<ArrayBufferLike> | Uint8Array<ArrayBufferLike>, options?: HashOptions): string

Signs a value with HMAC.

Parameters

NameType
valuestring | Buffer | Uint8Array
secretstring | Buffer | Uint8Array
optionsoptionalHashOptions

Returns string

nc.id.safeEqual()deprecated

Use nc.crypto.safeEqual(). This alias goes away in 3.0.

safeEqual(a: string | Buffer<ArrayBufferLike> | Uint8Array<ArrayBufferLike>, b: string | Buffer<ArrayBufferLike> | Uint8Array<ArrayBufferLike>): boolean

Compares two secrets in constant time.

Parameters

NameType
astring | Buffer | Uint8Array
bstring | Buffer | Uint8Array

Returns boolean

Types

Import any of them in TypeScript with import type { ParsedSnowflake } from "@ix-xs/node-comfort", or in JavaScript with import("@ix-xs/node-comfort").ParsedSnowflake.

ParsedSnowflake

A decoded Snowflake.

PropertyTypeDescription
dateDateWhen it was created.
timestampnumberWhen it was created, in ms.
workerIdnumber
processIdnumber
incrementnumberSequence number within the millisecond, 0 to 4095.

SnowflakeOptions

Options for snowflake() and parseSnowflake().

PropertyTypeDescription
epochoptionalnumberStart of time, in ms. Defaults to Discord's (2015-01-01). Twitter uses 1288834974657.
workerIdoptionalnumber0 to 31. Defaults to 0.
processIdoptionalnumber0 to 31. Defaults to process.pid % 32.

TokenEncoding

Encodings for token().

type TokenEncoding = "hex" | "base64" | "base64url" | "base58" | "base32"
node-comfort v2.0.0View the source