Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
Node.js Core & Express Backend APIs 20 mins read Free Lesson

JWT Authentication & Password Hashing in Node.js

Hash passwords securely with bcrypt and sign/verify JSON Web Tokens for stateless API authentication.

Secure Token Authentication

const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

async function hashPassword(plainText) {
    const saltRounds = 12;
    return await bcrypt.hash(plainText, saltRounds);
}

function generateToken(user) {
    return jwt.sign(
        { userId: user.id, email: user.email },
        process.env.JWT_SECRET,
        { expiresIn: '24h' }
    );
}