Stateless authentication using JSON Web Tokens (JWT) is the standard authentication model for modern web APIs, single-page React/Angular applications, and mobile apps. In this tutorial, you will implement secure password hashing with bcrypt and build complete authentication workflows.
npm install jsonwebtoken bcrypt
bcryptconst bcrypt = require('bcrypt');
// Hash password with 12 salt rounds before saving to database
async function hashUserPassword(plainPassword) {
const saltRounds = 12;
const hashedPassword = await bcrypt.hash(plainPassword, saltRounds);
return hashedPassword;
}
// Compare user-submitted login password with stored hash
async function verifyPassword(plainPassword, storedHash) {
const isMatch = await bcrypt.compare(plainPassword, storedHash);
return isMatch; // Returns true or false
}
const jwt = require('jsonwebtoken');
const JWT_SECRET = process.env.JWT_SECRET || 'super_secret_university_key_2026';
const JWT_EXPIRES_IN = '1h'; // Token valid for 1 hour
function signToken(userId, role) {
return jwt.sign(
{ id: userId, role: role }, // Claims Payload
JWT_SECRET, // Secret Key
{ expiresIn: JWT_EXPIRES_IN }
);
}
// middleware/verifyToken.js
const jwt = require('jsonwebtoken');
const protect = (req, res, next) => {
let token;
// Extract Bearer token from Authorization Header
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
token = req.headers.authorization.split(' ')[1];
}
if (!token) {
return res.status(401).json({ success: false, error: 'Access denied: No token provided' });
}
try {
// Verify token signature and expiration
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded; // Attach authenticated user payload to request
next(); // Proceed to protected route controller
} catch (err) {
return res.status(401).json({ success: false, error: 'Invalid or expired token' });
}
};
module.exports = protect;
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Protect tokens from XSS and CSRF attacks.
Build route-guard middleware with jwt.verify.
Underlying HMAC SHA-256 signatures in JWT.