MarquezMoore
MarquezMoore

Reputation: 9

What exactly does the Express.js next() function do and where does is live in the express package?

I am learning node.js and express.js in pursuit of becoming a full-stack javascript developer. Currently, I am learning express.js and the idea of middleware.

As I understand it, middleware is basically functions that have access to modify the request and response within the req-res cycle. Is this correct?

However, I am a bit gray in the idea of the next() function. I understand that it is designed to call the next middleware function in the flow of middleware functions, however, where does it come from. Where can I find it in the express.js package.

Upvotes: 1

Views: 729

Answers (1)

Yilmaz
Yilmaz

Reputation: 49361

When you have, more middlewares, they will run in order, and each middleware will pass the result to next middleware. imagine you have a route that can be accessed only by authenticated users.

  router.get("/products", adminController.getProducts);

this says, whenever a user makes a request to /products, run the controller for this route. However, if you want to show this route, only to authenticated users, you will write a custom middleware, check that a user is autenticated, is user authenticated you will let the adminController.getProducts otherwise you will show an error message. So you will be placing the middleware between.

    router.get("/products", isAuth, adminController.getProducts);

Note that you could pass more than one middleware. (adminController.getProducts is also a middleware but I mean besides isAuth you could place as many as you want) isAuth will be something like this:

export const isAuth = (req, res, next) => {   
  if (!req.session.isLoggedIn) {
    return res.redirect("/login");
  }
  next();
};

Imagine you setup a session based project. When user logs in, express-session (you will get familiar) will add session.isLoggedIn=true to the req obj. So before user attemps to react "/products", you will be checking if req.session.isLoggedIn is true. If yes you will let the next middleware to run, if not you will be redirecting the user to "/login" route.

Upvotes: 1

Related Questions