Crypto random

randomUUID

A UUID is a long random label with negligible collision odds. One call creates a text ID without counters or central coordination.

import { randomUUID } from "node:crypto"; const id: string = randomUUID(); console.log(id);

550e8400-e29b-41d4-a716-446655440000

randomBytes hex

Random bytes serve tokens of any chosen length. Hex encoding turns each byte into two readable characters, so size the byte count to half the wanted text length.

import { randomBytes } from "node:crypto"; const token: string = randomBytes(16).toString("hex"); console.log(token.length);

32

Timing-safe compare note

Plain equality can leak match length through response speed. The timing-safe helper compares full buffers in constant time for one length.

Only use it on same-length inputs, and hash secrets before storage. Treat this section as a concept note, not a full login system.

import { timingSafeEqual } from "node:crypto"; const a = Buffer.from("abc123"); const b = Buffer.from("abc123"); const same: boolean = a.length === b.length && timingSafeEqual(a, b); console.log(same);

IDs for records

Give each new record a fresh UUID at creation time. The ID then travels with the object through files, logs, and tests.

import { randomUUID } from "node:crypto"; const note = { id: randomUUID(), title: "Buy milk" }; console.log(note.id);

Never reuse IDs across records, and never derive them from titles. Random creation keeps references stable even after renames.

Next: Timers

Article author: Arthur Isaev