- Published on
How to Generate Unique IDs in JavaScript
- Authors
- Name
- Ashik Nesin
- @AshikNesin
Ever wondered to easily generate unique IDs that work in all platforms like browser, Node.js and Deno?
Here is how to do it using the built-in randomUUID() method:
Browser
const uuid = crypto.randomUUID();
console.log(uuid);
// 👉 56a0640d-148f-48e6-a2b7-8bb83bad64b8
Node - ESM
// const crypto = require('crypto')
import crypto from 'crypto';
const uuid = crypto.randomUUID();
console.log(uuid);
// 👉 56a0640d-148f-48e6-a2b7-8bb83bad64b8
Node - CommonJS
const crypto = require('crypto')
const uuid = crypto.randomUUID();
console.log(uuid);
// 👉 56a0640d-148f-48e6-a2b7-8bb83bad64b8
Happy generating IDs!