Topics in this subject
Node.js 3 min read Updated 11 Aug 2026

Authentication (JWT & bcrypt)

Hashing passwords securely and implementing stateless authentication using JSON Web Tokens.

🧑‍🏫 Sabse pehle — simple mein samjho#

Authentication mein do sabse zaroori rules hain:

  1. Kabhi bhi user ka asli password database mein save mat karo! Agar DB hack hua to sabke accounts udelenge. Isliye hum password ko hash (encrypt type) karke save karte hain (bcrypt).
  2. Jab user login kar le, toh server ko yaad rakhna chahiye ki ye user authenticated hai. Aisa karne ke liye hum usko ek VIP pass dete hain jise JWT (JSON Web Token) kehte hain. User har agayi request ke sath ye token bhejta hai, jisko check karke server pehchaan leta hai ki user kaun hai.

1. Hashing Passwords with bcryptjs#

When a user registers, you must hash their password before saving it.

const bcrypt = require('bcryptjs');

// In your Registration Route:
const plainPassword = req.body.password;

// The higher the salt rounds (e.g., 10 or 12), the more secure but slower the hashing.
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(plainPassword, salt);

// Save `hashedPassword` to the database instead of `plainPassword`!

When they login, you compare the entered password with the hashed password in the DB.

// In your Login Route:
const isValidPassword = await bcrypt.compare(enteredPassword, userFromDb.password);

if (!isValidPassword) {
    return res.status(401).json({ message: "Invalid credentials" });
}

2. JSON Web Tokens (JWT)#

A JWT is a string divided into three parts: Header, Payload (data), and Signature (encryption). It is stateless, meaning the server doesn't need to store the token in the database to verify it; it just verifies the signature using a secret key.

npm install jsonwebtoken

Issuing a Token (On successful login)#

const jwt = require('jsonwebtoken');

// Create a payload (don't put sensitive data like passwords here!)
const payload = { userId: userFromDb._id, role: "admin" };

// Sign the token using a secret key stored in your .env file
const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '1d' }); // Valid for 1 day

// Send it to the client
res.json({ token });

Verifying a Token (Protecting Routes)#

You create an Express middleware to protect specific routes. It extracts the token from the incoming request's Authorization header.

const protectRoute = (req, res, next) => {
    // Standard format: "Bearer <token>"
    let token = req.headers.authorization;

    if (!token || !token.startsWith('Bearer ')) {
        return res.status(401).json({ message: "Not authorized, no token" });
    }

    try {
        token = token.split(' ')[1]; // Extract just the token string
        
        // Verify the signature
        const decodedPayload = jwt.verify(token, process.env.JWT_SECRET);
        
        // Attach the user info to the request object so the next route can use it
        req.user = decodedPayload; 
        next();
    } catch (error) {
        res.status(401).json({ message: "Token failed or expired" });
    }
};

// Apply it to a route
app.get('/api/profile', protectRoute, (req, res) => {
    res.json({ message: `Welcome User ID: ${req.user.userId}` });
});

Security Note: Always store your JWT_SECRET in a .env file and never commit it to GitHub.