
Table of Contents
For this series, I'm following an excellent video tutorial fromTraversy Media
Introduction
In this blog, we'll dive into the development of a robust authentication system for your application. We'll start by creating aprotect
middleware that ensures the safety of our users' data.
Create protect middleware
Firstly, we'll start with creating anauthMiddleware.js
file in themiddleware
folder.
constjwt=require("jsonwebtoken");constasyncHandler=require("express-async-handler");constUser=require("../models/userModel");constprotect=asyncHandler(async(req,res,next)=>{lettoken;if(req.headers.authorization&&req.headers.authorization.startsWith("Bearer")){try{// get token from headertoken=req.headers.authorization.split("")[1];// verify tokenconstdecoded=jwt.verify(token,process.env.JWT_SECRET);// get user from the tokenreq.user=awaitUser.findById(decoded.id).select("-password");next();}catch(error){console.log(error);res.status(401);thrownewError("Not Authorized");}}if(!token){res.status(401);thrownewError("Not Authorized, no token");}});module.exports={protect};
In this function, we retrieve the token from the request headers and verify it to determine if the decoded token'sid
matches any user in the database. If it doesn't find a user or if the token is missing, in such cases, we throw an error.
Get current user data
Next, we'll create a function to get the currently logged-in user data inuserController.js
.
constgetLoggedInUser=asyncHandler(async(req,res)=>{const{_id,name,email}=awaitUser.findById(req.user.id);res.status(200).json({id:_id,name,email,});});
Protect the user data route
In the last, We'll useprotect
middleware to secure the user data route. Add these lines to theuserRoutes.js
file.
// import middlewareconst{protect}=require("../middleware/authMiddleware");...// Add a protect as a second paramrouter.get("/me",protect,getLoggedInUser);...
Now, let's check this functionality with no token
Now add the correct token
And now test it with an invalid token
That's it for today. In the next article, we'll work on protecting the todos routes.
Connect with me
Top comments(1)

- LocationDhaka
- EducationBSc in EEE
- WorkFront-End Developer
- Joined
A lot of things have to be learned and learned! Thanks
Could you add a frontendfolder/stracture so we can learn the structure and templating engine? I'm looking forejs
For further actions, you may consider blocking this person and/orreporting abuse