skip to Main Content

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


  1. 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

    if (req.userId == req.params.id) {
          next();
    }
    
    Login or Signup to reply.
  2. Every callback where you access req and res, you can also access next. 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:

    const firstCallback= (req, res, next) => {}
    const secondCallback= (req, res, next) => {}
    app.get("/", firstCallback);
    app.get("/", secondCallback);
    
    // or using this syntax
    app.get("/", firstCallback, secondCallback);
    

    In the above example, when a request comes to /, it’s handled first by firstCallback, and it’s one of the two below scenarios (otherwise the request will hang, and the user won’t get a response):

    1. It stops the request by calling one of the res methods, like res.status(401).json("not authorised");
    2. It says "pass to the next callback" calling next(), and then secondCallback handles it.

    If next is omitted from the parameters, you will be calling next() where it’s undefined, and that throws an error. Speaking of the use of protect function, if you notice, there is next as part of protectandauth‘s parameters, and it’s that next that’s used inside protect‘s third parameter, which is:

     () => {
        if (req.userId == req.params.id) {
          next();
        } else {
          res.status(401).json("not authorised");
        }
      }
    

    And in this specific code you have, the above function is passed as next in protect‘s definition.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search