Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
Difference between async(req,res,next) and async(req,res,()=>{}

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");
    }
  });
};
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Santiago Trujillo Denunciar

0

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();
}
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda