CodyBugstein
CodyBugstein

Reputation: 23322

Who provides the next() function in Express middleware?

I'm confused about how next() works in Node.js and Express middleware.

There have been some other questions about middleware works, for example here, but I'm looking for a different answer.

The main question bugging me is, who is providing the next() function?

For example, in my standard generated express app, I'm given this code:

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

But who calls this function and what is the nature of the next() that it provides? How do I know what the next() will look like? I have no idea what next() does.

Upvotes: 1

Views: 1835

Answers (1)

Or Guz
Or Guz

Reputation: 1018

An Express application is essentially a series of middleware calls.

Middleware is a function with access to the request object (req), the response object (res), and the next middleware in line in the request-response cycle of an Express application, commonly denoted by a variable named next.

As written above, Expressjs provides the next callback function. Next is just a way of calling the next middleware in the flow.

For many examples see Express's Using middleware

Upvotes: 2

Related Questions