Express.js Password Hashing
Password hashing converts a password into a scrambled string that cannot return to the original text. Apps store the scrambled string instead of the real password. A stolen database then reveals no usable passwords. Every app with user accounts needs this protection, and the bcrypt library makes it simple in Express.
Hashing Versus Encryption
Encryption locks data with a key and unlocks it with the same key. Hashing works in one direction only. No key exists that turns a hash back into the password. The app checks a login by hashing the typed password and comparing the two hashes.
| Feature | Encryption | Hashing |
|---|---|---|
| Direction | Two-way | One-way |
| Needs a key | Yes | No |
| Best use | Messages and files | Passwords |
The Blender Analogy
A blender turns a fruit into juice. Nobody can turn the juice back into the fruit. Two people who blend the same fruit with the same recipe get the same juice. The app blends the typed password on every login and compares the juice with the stored juice.
Why Plain Hashes Fall Short
Fast hash functions let attackers test billions of guesses per second. Attackers also keep tables of common passwords and their hashes. Two users with the same password would share the same hash. The bcrypt library solves these problems with two features.
Salt
A salt is a random string that bcrypt mixes into each password before hashing. Two users with the same password receive different hashes. Prebuilt guess tables become useless.
Cost Factor
The cost factor, also called salt rounds, controls how slow the hashing runs. Each increase doubles the work. A value of 10 or 12 stays fast for one login and costly for a mass guessing attack.
Hashing Flow Diagram
SIGN UP
Password "mango123"
|
v
bcrypt adds salt + runs 10 rounds
|
v
Hash "$2b$10$Nq7..." --> saved in database
LOGIN
Typed password "mango123"
|
v
bcrypt compares with the saved hash
|
Match -> access granted
No match -> access denied
Install bcrypt
npm install bcryptRegister a User
const express = require('express');
const bcrypt = require('bcrypt');
const app = express();
app.use(express.json());
const users = [];
app.post('/register', async (req, res) => {
const { email, password } = req.body;
const hash = await bcrypt.hash(password, 10);
users.push({ email, password: hash });
res.status(201).json({ message: 'User registered' });
});The hash function takes the password and the cost factor. It returns a promise that resolves to the final hash string. The app saves the hash and discards the password.
Log a User In
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = users.find((u) => u.email === email);
if (!user) {
return res.status(401).json({ error: 'Invalid email or password' });
}
const match = await bcrypt.compare(password, user.password);
if (!match) {
return res.status(401).json({ error: 'Invalid email or password' });
}
res.json({ message: 'Login successful' });
});The compare function reads the salt from the stored hash, hashes the typed password with it, and checks the result. The reply uses the same message for a wrong email and a wrong password. That choice hides which part failed and gives attackers no clue.
Hash Inside a Mongoose Model
Many apps hash passwords automatically before saving a user.
userSchema.pre('save', async function (next) {
if (!this.isModified('password')) return next();
this.password = await bcrypt.hash(this.password, 10);
next();
});
userSchema.methods.checkPassword = function (typed) {
return bcrypt.compare(typed, this.password);
};Best Practices
- Use the asynchronous hash and compare functions to keep the server responsive.
- Require a minimum password length of eight characters.
- Never log passwords or send them back in a response.
- Exclude the password field from query results with select('-password').
- Serve the login route over HTTPS only.
- Raise the cost factor as computers grow faster.
A strong hash protects users even when a breach happens. Pair hashing with rate limiting and token-based login for a complete defense.
