I recently came across this code and I fail to understand why the next
has been omitted from the protect
function(inside protectandauth
function) while it is included in the protect
function originally.
I want to know the difference between protect=async(req,res,next)
and protect=async(req,res,()=>{}
.
I also see that even though next
is omitted in the protect
(the one inside protectandauth
) function, it is still used in the code after the ‘if’ statement, how is that possible?
Code:
export const protect = async (req, res, next) => {
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
let token;
token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(token, "kris");
req.userId = decoded.id;
try {
req.user = await User.findById(req.userId).select("-password");
next();
} catch (error) {
res.status(401).json(error.message);
}
if (!token) {
res.status(404).json("no token found");
}
}
};
export const protectandauth = async (req, res, next) => {
protect(req, res, () => {
if (req.userId == req.params.id) {
next();
} else {
res.status(401).json("not authorised");
}
});
};
2
Answers
We use next if we want to pass our request to the next middleware in line. Maybe in protect, the programmer might not want to pass the req to the next middleware but in protectandauth he want to pass the req to the next middleware if this condition turns out to be true
Every callback where you access
req
andres
, you can also accessnext
.next
is a function that’s used to to say "pass to the next callback", knowing that a request can be processed by multiple callbacks, like so:In the above example, when a request comes to
/
, it’s handled first byfirstCallback
, and it’s one of the two below scenarios (otherwise the request will hang, and the user won’t get a response):res
methods, likeres.status(401).json("not authorised");
next()
, and thensecondCallback
handles it.If
next
is omitted from the parameters, you will be callingnext()
where it’sundefined
, and that throws an error. Speaking of the use ofprotect
function, if you notice, there isnext
as part ofprotectandauth
‘s parameters, and it’s thatnext
that’s used insideprotect
‘s third parameter, which is:And in this specific code you have, the above function is passed as
next
inprotect
‘s definition.