How to Hash Passwords in Node.js Using Bcryptjs, Express and Mongoose


Introduction

Storing plaintext passwords in a database is one of the most critical security vulnerabilities a web application can have. If a database is compromised, every user account is instantly exposed. To protect user credentials, modern backend applications rely on secure cryptographic hashing functions like bcrypt.

In this tutorial, we will walk through how to build a secure user registration and login API in Node.js using Express, Mongoose, and bcryptjs.


What is Bcrypt?

Bcrypt is a password-hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher, and introduced at USENIX in 1999.

  • Built-in Salt Protection: Bcrypt automatically incorporates a salt (random data) into the hashing process to protect against rainbow table attacks.

  • Adaptive Work Factor: It is an adaptive function, meaning the iteration count (cost factor) can be increased over time to keep pace with growing computer processing power, making it highly resistant to brute-force attacks.


What is Hashing? 

Hashing is a one-way cryptographic mapping function. It transforms any input string (like a user's password) into a fixed-length string of characters.

  • Irreversible: You cannot reverse a hash to retrieve the original plain-text string.

  • Verification: To check a login password, you hash the incoming plain-text string with the stored salt and compare the resulting hash strings.


Step 1: Project Setup and Dependencies


1. Create and Enter Project Directory

   
Open your terminal and run the following commands:
    
     mkdir bcrypt
     
     cd bcrypt

2. Initialize Node.Js

Initialize your workspace to generate a package.json configuration file:

npm init -y

3.Install Required Pacakges

Install Express, Mongoose, bcryptjs, and Body-Parser:

npm install --save bcryptjs express body-parser mongoose

Pacakges BreakDown

  • Express: Fast, unopinionated web framework for building APIs and web applications.

  • Body-Parser: Middleware to extract incoming request bodies and expose them on req.body.

  • Mongoose: An Object Data Modeling (ODM) library for MongoDB and Node.js that handles schema validation and database queries.

  • Bcryptjs: A pure JavaScript implementation of Bcrypt for hashing and comparing passwords securely.


Step 2: Create the Mongoose User Model(models/user.js)


Create a folder named models and add a file named user.js.

Mongoose schemas map directly to MongoDB collections and define the structure of documents within them.

var mongoose = require('mongoose');

var userSchema =  new mongoose.Schema({
    email:String,
    password:String
});

module.exports = mongoose.model('user',userSchema);


Step 3: Build the Entry Point & Authentication Logic(app.js)


Create app.js in your root directory. This file handles database connections, registration (hashing passwords), and login (comparing hashes).

var express     = require('express');
var bodyParser  = require('body-parser');
var mongoose    = require('mongoose');
var userModel   = require('./models/user');
var bcrypt      = require('bcryptjs');

//set the connection to db
mongoose.connect('mongodb://localhost:27017/Demoo',{useNewUrlParser:true})
.then(function(){
    console.log('connected to db');
}).catch(function(error){
    console.log('error'+error);
});

var app = express();

//fetch data from request
app.use(bodyParser.json());

//register user
app.post('/register',function(req,res){
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(req.body.password, salt, function(err, hash) {
          var userr = new userModel({
              email:req.body.email,
              password:hash
          });
          userr.save(function(err,data){
              if(err){
                  res.json({er:error});
              }else{
                  res.json({da:data,msg:'user is registerd'});
              }
          });
        });
    });
});

//user login
app.post('/login',function(req,res){
    userModel.find({email:req.body.email},function(err,data){
        if(err){
            res.json({er:err});
        }else{
            if(data!=''){
                bcrypt.compare(req.body.password,data[0].password, function(err, result) {
                     if(result){
                          res.json({msg:'password matched'});
                     }else{
                         res.json({msg:'password didnt matched'});
                     }
                });
            }
            else{
                res.json({msg:'user is not registerd'});
            }
        }
    });
});

var port = process.env.PORT || 3000;
app.listen(port,function(){
    console.log('server running at '+port);
});


Reference


Video Tutorial: :- Watch Video Tutorial






Comments

Popular posts from this blog

How to Setup a Flask Project in Python: Step-by-Step Guide

How to Use Sequelize-CLI to Create Tables and Relationships in Node.js