Search code examples
node.jsexpressrandom

NodeJS: How do I generate a random hex key for password reset?


I am developing a express js end point and I need to send some random hex-decimal code

I am trying to generate a random hex key for a reset password process in nodejs. Can anyone help? Is there any library? Or shell I use some standard code
Shell I also sign the code like with jwt?


Solution

  • So let see if I can help

    The first way is the js without any library

    const randomizer = (length) =>{
      const pullOfChars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";
      const generatedArrayOfChars = Array.from(
        { length: length },
        (v, k) => pullOfChars[Math.floor(Math.random() * pullOfChars.length)].toString(16)
      );
    
      const randomizedString = generatedArrayOfChars.join("");
      return randomizedString
      
    }
    
    console.log(randomizer(10))

    Or you can use the of node js crypto

    const crypto = require('crypto');
    
    const randomString1 = crypto.randomBytes(10).toString('hex');
    console.log(randomString1);
    

    hope it helps