brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: crypto.randomUUID() creates a random ID without a package

Javascript
~/tips/tip-javascript-crypto-randomuuid

const id = crypto.randomUUID();

Returns a random version 4 UUID from the browser's secure random generator.

For an id of a row, a file or a temporary key, I used to see people install a package. The browser has it built in.

const id = crypto.randomUUID();
console.log(id); // for example 36b8f84d-df4e-4d49-b662-bcde71a8764f

The method returns a 36 character string with a version 4 UUID, generated with a cryptographically secure random number generator. Node.js has the same function in its crypto module.

It is a good fit for client-generated ids, such as items in an offline-first app, element ids or a request id that you put in a log line.

MDN says it has been available across browsers since July 2015. It also works in Web Workers.

The caveat is the secure context. randomUUID() only exists on pages served over HTTPS, and on localhost. On a plain http://192.168.x.x page, which is common for a self-hosted app on a home network, crypto.randomUUID is simply undefined and your code throws. The older crypto.getRandomValues() is the one member that works in an insecure context, so keep a fallback built on it if your app runs over plain HTTP. Test it once by opening the page through its IP address instead of the HTTPS name, and you will see the difference straight away. Test it once by opening the page by its IP address instead of through your HTTPS name.

Further reading: MDN: Crypto.randomUUID()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link