What is the correct way to create a cryptographically secure ID in BOTH node.js and javascript without libraries?

Viewed 32

I'm tying to write an ES6 module that detects which environment it is running on and create a unique hex ID if it is node, or if it is browser. I do not want to use browser libraries or a bundler.

In node.js:

const crypto = require('crypto')
let id = crypto.randomBytes(48, function(err, buffer) {
  return buffer.toString('hex')
})
console.log(id)

In both browser and node without a bundler:

???? unsure, from on my research on how to accomplish the same thing.
1 Answers

Node 15+ and modern browsers support the Web Crypto API

export async function setupHexRandom(){
  const mycrypto = (typeof crypto !== 'undefined')
     ? crypto
     : (await import('node:crypto')).webcrypto

  if (!mycrypto) throw new Error('No crypto available or fallback to a Math.random implementation')

  return function hexRandom(){
    const bytes = mycrypto.getRandomValues(new Uint8Array(48))
    return Array.from(bytes)
      .map(b => b.toString(16).padStart(2, '0'))
      .join('')
  }
}

const hexRandom = await setupHexRandom()
console.log(hexRandom())
Related