How to Hash and Salt Passwords for Secure Database Storage with Node.js?

Table of contents

No heading

No headings in the article.

  1. Install the bcrypt library:

     npm install bcrypt
    
  2. In your user registration route, hash the password using bcrypt:

     const bcrypt = require('bcrypt');
    
     // ...
    
     // Hash password
     const saltRounds = 10;
     const salt = await bcrypt.genSalt(saltRounds);
     const hash = await bcrypt.hash(req.body.password, salt);
    
     // Save user to database with hashed password
     const user = new User({
       username: req.body.username,
       password: hash,
     });
     await user.save();
    
  3. In your user login route, compare the hashed password in the database with the input password using bcrypt:

     const bcrypt = require('bcrypt');
    
     // ...
    
     // Get user from database
     const user = await User.findOne({ username: req.body.username });
    
     // Compare password
     const passwordMatch = await bcrypt.compare(req.body.password, user.password);
     if (!passwordMatch) {
       // Passwords do not match
       return res.status(401).send('Invalid username or password');
     }
    
     // Passwords match - create access token and return it to the user
     const accessToken = jwt.sign({ userId: user._id }, process.env.ACCESS_TOKEN_SECRET);
     res.json({ accessToken });
    
  4. To store access tokens in the database, you can create a separate collection/table for tokens and store the token along with the user ID and expiration date. Here is an example using MongoDB and Mongoose:

     const mongoose = require('mongoose');
    
     const tokenSchema = new mongoose.Schema({
       userId: {
         type: mongoose.Schema.Types.ObjectId,
         ref: 'User',
         required: true,
       },
       token: {
         type: String,
         required: true,
       },
       expiresAt: {
         type: Date,
         required: true,
       },
     });
    
     const Token = mongoose.model('Token', tokenSchema);
    
     // ...
    
     // Save access token to database
     const token = new Token({
       userId: user._id,
       token: accessToken,
       expiresAt: new Date(Date.now() + 3600 * 1000), // expires in 1 hour
     });
     await token.save();
    

These are just some examples of how to securely store passwords and access tokens in a database using Node.js. It is important to follow best practices and ensure that your application is properly secured.

Did you find this article valuable?

Support Bit Fetch by becoming a sponsor. Any amount is appreciated!