- Create a MongoDB database and a collection to store user data.
- Create an Express.js server to handle requests from the client-side.
- Install the necessary packages such as
bcryptjs
for password encryption,jsonwebtoken
for user authentication, andbody-parser
for parsing incoming request bodies. - Create a user model and schema for storing user data in the database.
- Create routes for handling login requests. These routes should handle POST requests with the user’s email and password, check if the email exists in the database, and then verify the password using
bcryptjs
. If the password is correct, create a JSON Web Token (JWT) to authenticate the user. - On the client-side, create a login form that sends a POST request to the server with the user’s email and password.
- When the server responds with a JWT, store it in the browser’s local storage or a cookie to keep the user authenticated.
LOGIN API
create controller folder and that folder in create userdata.js and add this code.

const User = require(“../model/userSchema”);
const bcrypt = require(‘bcrypt’);
const jwt = require(‘jsonwebtoken’);
const login = async(req,res) =>{
try {
const {email,password}= req.body;
if(!email || !password){
return res.status(400).json({error:”please filled the data”})
}
const userLogin = await User.findOne({email:email});
console.log(userLogin);
if (userLogin) {
const isMatch = await bcrypt.compare(password,userLogin.password);
const token = await userLogin.generateAuthToken();
console.log(token);
if(!isMatch){
res.status(400).json({error:”Invalid detail”})
}else {
res.json({message:” login successfully”});
}
}
else{
res.status(400).json({error:”Invalid detail”});
}
} catch (error) {
console.log(error);
}
};
module.exports = {login};
this code add in index.js

var express = require(‘express’);
var router = express.Router();
var {login}= require(“../controller/userdata.js”);
/* GET home page. */
router.route(“/login”).post(login);
module.exports = router;
create jsonwebtoken in schema

const mongoose = require(‘mongoose’);
const bcrypt = require(‘bcrypt’);
const jwt = require(‘jsonwebtoken’);
const userSchema = new mongoose.Schema({
name:{type:String,required:true},
email:{type:String, required:true},
password:{type:String,required:true},
tokens:[
{
token:{type:String,required:true}
}]
})
userSchema.methods.generateAuthToken = async function (){
try {
console.log(this._id);
const token = jwt.sign({_id:this._id.toString()}, process.env.SECRET_KEY);
this.tokens = this.tokens.concat({token:token})
await this.save();
return token;
} catch (error) {
console.log(error);
}};
userSchema.pre(“save”, async function(next){
if(this.isModified(“password”)){
this.password = await bcrypt.hash(this.password,12);
}
next();
});
const User = mongoose.model(“user”,userSchema);
module.exports = User;