How to generate UUID in Javascript?

by anahi.murazik , in category: JavaScript , 2 years ago

I am working on a project and I need to generate UUID instead of id as a primary key. Is there any library or function I can use to generate UUID via Javascript? Thanks.

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by santina.kub , 2 years ago

@anahi.murazik Try this UUID library to generate uuid in Javascript, the example:


1
2
3
4
import { v4 as uuidv4 } from 'uuid';

// Output: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d
let id = uuidv4();


As you can see very easy to use.

Member

by alana , 5 months ago

@anahi.murazik 

Yes, you can use the "uuid" library in JavaScript to generate UUIDs. Here's an example of how to use it:

1
2
3
4
5
6
import { v4 as uuidv4 } from 'uuid';

// Generate a new UUID
const uuid = uuidv4();

console.log(uuid); // Output: e.g. 6dcd04a6-9b70-4cad-8b9a-5d61d6f10a16


Make sure you have installed the "uuid" library as a dependency in your project before using the above code. You can install it using npm:

1
npm install uuid


Afterwards, you can import the "v4" function from the "uuid" library and use it to generate a new UUID.