How to generate unique pc/device ID in ReactJS? Multi-device login restrict purpose

4.1k views Asked by At

Developing a web apps using ReactJS. I need to ensure that no user can login to multiple device at the same time. To identify the device I need to to generate a unique device ID. I tried a lot of answers but didn't find any proper solution for reactjs/javascript. I tried to collect OS/PC information and generate by myself but all I got only oscpu: "Windows NT 10.0; Win64; x64" platform: "Windows NT" using window.navigator.

Please help to generate an unique PC ID.

1

There are 1 answers

2
eric anthony On

you can use Math.random() for that or using

<script>
var crypto = require("crypto");
    var id = crypto.randomBytes(20).toString('hex');
    console.log(id)
    // "bb5dc8842ca31d4603d6aa11448d1654"
</script>

  • using uuid module

<script>
var uuid = require("uuid");
    var id = uuid.v4();
    console.log(id)
    // "110ec58a-a0f2-4ac4-8393-c866d813b8d1"
</script>

  • or using your own logic code

<script>
// dec2hex :: Integer -> String
    // i.e. 0-255 -> '00'-'ff'
    function dec2hex (dec) {
      return dec < 10
        ? '0' + String(dec)
        : dec.toString(16)
    }
    
    // generateId :: Integer -> String
    function generateId (len) {
      var arr = new Uint8Array((len || 40) / 2)
      window.crypto.getRandomValues(arr)
      return Array.from(arr, dec2hex).join('')
    }
    
    console.log(generateId())
    // "82defcf324571e70b0521d79cce2bf3fffccd69"
    
    console.log(generateId(20))
    // "c1a050a4cd1556948d41"
</script>

answer based on this

for best practices, you can integrate with a backend server and databases for perfect unique ids to databases