Published:

Node.js - Hash and Verify Passwords with Bcrypt

This is a quick example of how to hash and verify passwords in Node.js using the bcryptjs password hashing library which is a pure JavaScript implementation of the bcrypt password hashing function.

For more info on the bcryptjs password hashing JavaScript library see https://www.npmjs.com/package/bcryptjs.

For more info on the underlying bcrypt password hashing function, see https://en.wikipedia.org/wiki/bcrypt.


Installing bcryptjs from npm

With the npm CLI: npm install bcryptjs

With the yarn CLI: yarn add bcryptjs


Hashing a password in Node.js

This code hashes the password 'Pa$$w0rd' using bcrypt and stores the result in the passwordHash variable.

const passwordHash = bcrypt.hashSync('Pa$$w0rd', 10);


Verify a password against a hash in Node.js

This code verifies the password 'Pa$$w0rd' using bcrypt against the hash stored in the passwordHash variable.

const verified = bcrypt.compareSync('Pa$$w0rd', passwordHash);


Example usage in an Account Service

Below is an example account service with a register() method that saves an account with a hashed password and an authenticate() method that verifies a provided password against the passwordHash of a saved account.

The service is a simplified version of the account service from a boilerplate api project I posted recently, for more info and to test out the service in a fully functioning project see Node + Mongo - Boilerplate API with Email Sign Up, Verification, Authentication & Forgot Password.

const bcrypt = require('bcryptjs');
const db = require('_helpers/db');

module.exports = {
    authenticate,
    register
};

async function register(params) {
    // create account object
    const account = new db.Account(params);

    // hash password
    account.passwordHash = bcrypt.hashSync(params.password, 10);

    // save account
    await account.save();
}

async function authenticate({ email, password }) {
    // get account from database
    const account = await db.Account.findOne({ email });

    // check account found and verify password
    if (!account || !bcrypt.compareSync(password, account.passwordHash)) {
        // authentication failed
        return false;
    } else {
        // authentication successful
        return true;
    }
}

 

Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter or GitHub to be notified when I post new content.

 


Supported by