Performance: Password hashing with bcrypt
This affects server response time during user authentication and registration by adding CPU work for hashing passwords.
Jump into concepts and practice - no test required
const bcrypt = require('bcrypt'); app.post('/signup', async (req, res) => { const password = req.body.password; const hashed = await bcrypt.hash(password, 12); // recommended salt rounds // save hashed password res.send('User created'); });
const bcrypt = require('bcrypt'); app.post('/signup', async (req, res) => { const password = req.body.password; const hashed = await bcrypt.hash(password, 4); // low salt rounds // save hashed password res.send('User created'); });
| Pattern | CPU Load | Blocking Behavior | Response Delay | Verdict |
|---|---|---|---|---|
| bcrypt with low salt rounds | Low CPU | Non-blocking (async) | Fast response | [X] Bad |
| bcrypt with recommended salt rounds | Medium CPU | Non-blocking (async) | Moderate delay | [OK] Good |
| bcrypt with recommended salt rounds (sync) | Medium CPU | Blocking | High delay | [X] Bad |
| No hashing or weak hashing | Minimal CPU | Non-blocking | Fast but insecure | [X] Bad |
bcrypt in an Express app?await and two arguments: the password and salt rounds.await bcrypt.hash(password, 10); which is correct async usage. const hashed = bcrypt.hashSync(password, 10); is synchronous, C is wrong function, B misses salt rounds.const bcrypt = require('bcrypt');
async function test() {
const password = 'secret123';
const hash = await bcrypt.hash(password, 5);
const match = await bcrypt.compare('secret123', hash);
console.log(match);
}
test();bcrypt.compare returns true, which is logged.app.post('/signup', async (req, res) => {
const { password } = req.body;
const hashed = bcrypt.hash(password, 10);
// Save hashed password to DB
res.send('User created');
});await to get the hashed string.await, hashed is a Promise, not the actual hash, causing errors when saving.