Generate unique identifiers for items
Quick Answer
Use `crypto.randomUUID()` in modern environments for a collision-proof UUID. The Date + `Math.random` fallback is lightweight and sufficient for temporary client-side keys.
1const generateId = () => {
2 return Date.now().toString(36) + Math.random().toString(36).substring(2);
3};
4
5// Or using crypto for better randomness
6const generateSecureId = () => {
7 return crypto.randomUUID();
8};Unique IDs are needed whenever you create items without an immediate database-assigned ID. crypto.randomUUID() is the modern standard, available in all current browsers and Node.js 15+. The Date-based fallback is lightweight and collision-resistant enough for client-side temporary keys.
Use `crypto.randomUUID()` for client-generated IDs, optimistic UI updates, or offline-first apps. Use database-generated IDs (serial, UUID with default) when the server controls ID assignment and uniqueness across all clients.
This free javascript code snippet for generate unique id is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement generate unique id quickly and correctly.
All snippets in the Snippetly library follow javascript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses javascript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.