For more tips like this, sign up to the weekly newsletter!

Use the Web Crypto API to generate hashes

With the new crypto APIs supported in the browsers, you no longer need an external library to generate the hash of a value.

The function that does that is the crypto.subtle.digest(algo, buffer). It returns a Promise with the result as an ArrayBuffer. And since it also expects a Buffer, you'll need some conversions to provide a hex string.

To calculate the SHA-1 hash of a string, use:

// encode as UTF-8
const msgBuffer = new TextEncoder('utf-8').encode(message);

// hash the message
const hashBuffer = await crypto.subtle.digest("sha-1", msgBuffer);

// convert ArrayBuffer to Array
const hashArray = Array.from(new Uint8Array(hashBuffer));

// convert bytes to hex string
const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
return hashHex;

The supported algorithms are SHA-1, SHA-256, SHA-384, and SHA-512.

Just keep in mind that it is an asynchronous function, so either you'll need to handle Promises directly, or use async/await.

Try it
References
Learn more: