Secure Password Hashing with Bcrypt in Express using JavaScript #js #javascript #mern

Posted by


In this tutorial, we will learn how to hash passwords using bcrypt.js in an Express application. Hashing passwords is an essential step in securing user authentication in web applications. Bcrypt.js is a popular library in the JavaScript community that helps to securely hash passwords.

We will be using a MERN stack (MongoDB, Express, React, Node.js) for this tutorial, but the concepts can be applied to any JavaScript application.

Step 1: Setting up the Express application
First, let’s create a new Express application using the following commands:

npm install express bcrypt mongoose

This will install Express, bcrypt, and mongoose packages in your project.

Next, create a new file called app.js and set up a basic Express application:

const express = require('express');
const app = express();

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Step 2: Setting up MongoDB connection
Next, let’s set up a connection to the MongoDB database using mongoose. Add the following code to your app.js file:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myapp', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('Connected to MongoDB');
});

Step 3: Hashing passwords using bcrypt
Now, let’s create a user model and hash the passwords using bcrypt. Add the following code to your app.js file:

const bcrypt = require('bcrypt');

const UserSchema = new mongoose.Schema({
  username: { type: String, required: true },
  password: { type: String, required: true },
});

UserSchema.pre('save', async function(next) {
  const user = this;

  if (!user.isModified('password')) {
    return next();
  }

  const hash = await bcrypt.hash(user.password, 10);
  user.password = hash;
  next();
});

const User = mongoose.model('User', UserSchema);

In this code snippet, we create a UserSchema with username and password fields. We use the pre middleware to hash the password before saving it to the database. The password is hashed with a cost factor of 10, which determines the complexity of the hash.

Step 4: Create a new user
Now, let’s create a new user and save it to the database. Add the following code to your app.js file:

const newUser = new User({
  username: 'admin',
  password: 'password123',
});

newUser.save((err) => {
  if (err) {
    console.error(err);
  } else {
    console.log('User created successfully');
  }
});

This code snippet creates a new user with the username admin and the password password123. When the user is saved to the database, the password will be automatically hashed using bcrypt.

Step 5: Verifying passwords
When a user logs in, you need to verify their password against the hashed password stored in the database. Add the following code to your app.js file:

app.post('/login', async (req, res) => {
  const { username, password } = req.body;

  const user = await User.findOne({ username });

  if (!user) {
    return res.status(400).json({ message: 'User not found' });
  }

  const isMatch = await bcrypt.compare(password, user.password);

  if (isMatch) {
    res.json({ message: 'Login successful' });
  } else {
    res.status(401).json({ message: 'Invalid password' });
  }
});

In this code snippet, we create an Express route for user login. We find the user in the database based on the username provided in the request. We then use the compare method of bcrypt to compare the hashed password stored in the database with the password provided in the request.

Conclusion
In this tutorial, we learned how to hash passwords using bcrypt.js in an Express application. By hashing passwords, we can secure user authentication and protect user data from unauthorized access. Bcrypt.js is a powerful library that makes password hashing easy and secure.