Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

crypto.randomUUID is not a function

I'm very new to JS, I want to generate a UUID. Here's what I tried, step by step:

  1. mkdir test
  2. cd test
  3. touch file1.js
  4. Inside file1.js:
let crypto;
try {
  crypto = require('crypto');
} catch (err) {
  console.log('crypto support is disabled!');
}

var uuid = crypto.randomUUID();
console.log(uuid);

And you see the error:

TypeError: crypto.randomUUID is not a function
    at Object.<anonymous> (/home/runner/yplebns1ahn/index.js:9:19)
    at Module._compile (internal/modules/cjs/loader.js:999:30)

What is wrong? I can't find an answer anywhere. Node JS version:

node -v shows v12.22.9

screenshot showing code and error

like image 632
Brian Brown Avatar asked Sep 06 '25 03:09

Brian Brown


1 Answers

here you can use randomBytes() method for get unique id

const crypto = require('crypto');
console.log(crypto.randomBytes(20).toString('hex'));

you can also use uuidv4 instead of crypto

const { uuid } = require('uuidv4');
console.log(uuid());
like image 137
Mr.Developer Avatar answered Sep 07 '25 20:09

Mr.Developer