Secure your Node.js API using salted bcrypt password hashing and stateless JSON Web Tokens (JWT).
⊞Code Example
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
// 1. Password Hashing
async function hashPassword(plainText) {
const salt = await bcrypt.genSalt(10);
return await bcrypt.hash(plainText, salt);
}
// 2. Generating JWT
function generateToken(userId) {
return jwt.sign({ id: userId }, process.env.JWT_SECRET, { expiresIn: '7d' });
}
// 3. Auth Guard Middleware
function verifyToken(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Unauthorized: No token provided' });
}
const token = authHeader.split(' ')[1];
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.userId = decoded.id;
next();
} catch (err) {
return res.status(403).json({ error: 'Forbidden: Invalid token' });
}
}
