Generating Unique IDs in JavaScript (Without a Library)
Often, you'll see people create their functions to generate a random string to use as an ID. But did you know JS has a built-in function to create a UUID?
This is available by calling randomUUID()
via crypto
.
It's baked right into the language, so there's no need for external packages. Here are examples of it in action:
Browser
In the Browser you need no imports and can simply use crypto.randomUUID();
:
const uuid = crypto.randomUUID(); console.log(uuid); // Output will be something like: "32458483-11c1-4334-bd64-a139f0de1bca"
Serverside
For serverside JS, the only difference is you need to import the crypto
module:
Start by importing the crypto module, then generate the UUID:
// If using CommonJS, replace the import with: const crypto = require("crypto") import crypto from "crypto"; const uuid = crypto.randomUUID(); console.log(uuid); // Output will be something like: "32458483-11c1-4334-bd64-a139f0de1bca"
Easy, right?
Notes:
If you are wondering, the randomUUID()
method generates a v4 UUID using a cryptographically secure random number generator.