One of the more frustrating limitations of vanilla JavaScript is that there is actually no GUID or UUID generator in the language. That’s right, out of the box, you cannot generate a GUID with a nice single line of code! Very annoying.
Luckily, there are two ways that I’ve used in the past to generate GUID or GUID-like strings.
This first piece of code is one I use in places where the randomness isn’t such a big deal. It might be just generating correlation ids, or just as a way to generate some randomized letters/numbers, but not global uniqueness and/or collisions aren’t such a big deal.
generateGuid() : string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
In most cases where I’m generating a GUID on the front end, I’m not worried too much about how secure things are. You shouldn’t be too concerned on collisions in the browser anyway because a user could just as easily inject JavaScript and/or modify an API call that uses the GUID into using their own string.
However, for a more secure GUID, there is obviously an NPM package for that!
npm install uuid
Then use the uuidv4 function to generate guids as you need them!
import { v4 as uuidv4 } from 'uuid';
let myGuid = uuidv4();
Again, in most cases I just use the first function. But I know people come up with all sorts of links on how “Math.random()” isn’t truly random etc. So both options are there!
💬 Leave a comment