SyntaxStudy
Sign Up
Node.js Password Hashing with bcrypt
Node.js Beginner 9 min read

Password Hashing with bcrypt

Never store plain-text passwords. bcrypt is an adaptive hashing algorithm designed for passwords. It automatically applies a salt and is intentionally slow to resist brute-force attacks. The cost factor controls the slowness.

Example
// npm install bcrypt
const bcrypt  = require('bcrypt');
const express = require('express');
const app     = express();
app.use(express.json());

const SALT_ROUNDS = 12; // Higher = slower = more secure

// Register: hash the password before saving
app.post('/register', async (req, res) => {
    try {
        const { username, password } = req.body;
        if (!username || !password) {
            return res.status(400).json({ error: 'username and password required' });
        }
        if (password.length < 8) {
            return res.status(400).json({ error: 'Password must be at least 8 characters' });
        }
        const hash = await bcrypt.hash(password, SALT_ROUNDS);
        // Save { username, password: hash } to your database
        console.log('Hashed password:', hash);
        res.status(201).json({ message: 'User registered' });
    } catch (err) {
        res.status(500).json({ error: 'Registration failed' });
    }
});

// Login: compare password to stored hash
app.post('/login', async (req, res) => {
    try {
        const { password } = req.body;
        const storedHash = '$2b$12$exampleHashFromDatabase'; // from DB
        const match = await bcrypt.compare(password, storedHash);
        if (!match) return res.status(401).json({ error: 'Invalid credentials' });
        res.json({ message: 'Login successful' });
    } catch (err) {
        res.status(500).json({ error: 'Login failed' });
    }
});

app.listen(3000);