DEV Community

mkaychuks
mkaychuks

Posted on

Password Hashing using bcrypt

Authentication is a very important aspect of web development, and as beginners, it can seem like a daunting task. In this brief tutorial, we would learn how to hash passwords during user signup/registration.

Pre-requisites

  1. Basic knowledge of JavaScript.
  2. expressJS
  3. bcrypt package

Create a folder on your local machine, and create a file app.js. we would put every code in this single file.

const express = require("express");
const bcrypt = require("bcrypt")

const app = express(); // init express app

app.listen(5000, () => {
   console.log('Server listening on port 5000...')
})
Enter fullscreen mode Exit fullscreen mode

We wouldn't be using a database in this tutorial but a array to pass the lesson across. We would create an async-await function for the password hash.

const express = require("express");
const bcrypt = require("bcrypt")

const app = express(); // init express app

app.use(express.json()) // accepting json body-parsers

const users = [] // we would be using as local storage

// creating a function for the password hash
const hashPassword = async (password) => {
  try {
    const salt = await bcrypt.genSalt();
    const hashedPassword = await bcrypt.hash(password, salt);
    return hashedPassword;
  } catch (error) {
    console.error(error);
  }
};

// Server up and running
app.listen(5000, () => {
   console.log('Server listening on port 5000...')
})
Enter fullscreen mode Exit fullscreen mode

Now, it is time to use the password hash function we created above to hash passwords. And the empty users array as our local storage.

const express = require("express");
const bcrypt = require("bcrypt")

const app = express(); // init express app

app.use(express.json()) // accepting json body-parsers

const users = [] // we would be using as local storage

// creating a function for the password hash
const hashPassword = async (password) => {
  try {
    const salt = await bcrypt.genSalt();
    const hashedPassword = await bcrypt.hash(password, salt);
    return hashedPassword;
  } catch (error) {
    console.error(error);
  }
};

// sending a post request to create a user
app.post(async (req, res) => {
    const passwordHash = await hashPassword(req.body.password)
    try {
    const user = {username: req.body.username, password: 
               passwordHash}
    users.push(user);
    res.status(201).json(user); 
/*
would return the user if you are using postman, 
you can as well console.log(user) to see the result in the terminal
*/
    } catch (error){
      console.error(error)
    }
})

// Server up and running
app.listen(5000, () => {
   console.log('Server listening on port 5000...')
})
Enter fullscreen mode Exit fullscreen mode

I believe things worked out on your own end, while following this tutorial..

Thanks for reading..

Top comments (0)