Javascript Mistakes: UUID generation with Math.random()?

Published: 03 May 2023
on channel: Th30z Code
525
12

Do not use Math.random() to generate UUIDs or any ID.

Using a pseudo-random number generator (PRNG) for generating UUID v4 is a bad idea because PRNGs have a limited period of randomness, which means that over time, the same sequence of values will be generated. This can lead to collisions and undermine the uniqueness of the UUIDs. Additionally, PRNGs may be predictable or susceptible to cryptographic attacks, which can compromise the security of the UUIDs. To ensure the uniqueness and security of UUIDs, a true random number generator should be used instead of a PRNG.

Read more about number generators: https://v8.dev/blog/math-random

The standard Crypto API has methods to generate random UUIDs and cryptographically strong random values:
https://developer.mozilla.org/en-US/d...
https://developer.mozilla.org/en-US/d...

Be aware that libraries published on NPM can have this kind of mistakes too:
See the deprecation warning of https://www.npmjs.com/package/uuid/v/... as an example.

#shorts #javascript #typescript #coding #programming #codingtips


On this page of the site you can watch the video online Javascript Mistakes: UUID generation with Math.random()? with a duration of hours minute second in good quality, which was uploaded by the user Th30z Code 03 May 2023, share the link with friends and acquaintances, this video has already been watched 525 times on youtube and it was liked by 12 viewers. Enjoy your viewing!