Categories
JavaScript Answers

How to hash passwords with Node.js?

Spread the love

To hash passwords with Node.js, we use the bcrypt package.

For instance, we write

import * as bcrypt from "bcrypt";

export const Encrypt = {
  cryptPassword: async (password) => {
    const salt = await bcrypt.genSalt(10);
    const hash = await bcrypt.hash(password, salt);
    return hash;
  },
  comparePassword: async (password, hashPassword) => {
    return await bcrypt.compare(password, hashPassword);
  },
};

to call genSalt to create a salt in the cryptPassword function.

Then we call hash to hash the password with the salt.

And then we call bcrypt.compare to compare the raw password with the hashedPassword with compare.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.