Bcrypt and JWT

1. First we need to install few dependencies.

npm i cookie-parser jsonwebtoken bcryptjs

2.Define a secret key in .env file.

config/.env
JWT_SECRET_KEY="kyaLekrAayeTheKyaLekarJana"
JWT_EXPIRES_IN=10d

3. Create a generate token function.

controllers/userController.js
const generateToken=(user)=>{
    return jwt.sign({
        userId:user._id,
        username:user.username,
        email:user.email
    },
    process.env.JWT_SECRET_KEY,
    {expiresIn:process.env.JWT_EXPIRES_IN}
)
}

4. Hash the password and store in Database. Send the jwt as cookies.

controllers/userController.js
exports.registerUser=async(req,res)=>{
    const {username,email,password,confirmPassword}=req.body;

    //if email already exists
    //other code

    //incorrect format of email
    //other code

    //passwords don't match
    //other code

    try {
        const hashedPassword=await bcrypt.hash(password,10);

        const newUser=new User({
            username,
            email,
            password:hashedPassword
        })

        await newUser.save();

        //generate jwt token
        const token=generateToken(newUser);

        //set token in cookies
        res.cookie('token',token,{
            httpOnly:true,
            secure:true,
            maxAge:864000000
        })

        res.status(201).json({
            message:"User registered successfully"
        })
    } catch (error) {
        res.status(500).json({ message: "Server error", error });
    }
}

CONTENT