Before understanding next
, you need to have a little idea of Request-Response cycle in node though not much in detail.
It starts with you making an HTTP request for a particular resource and it ends when you send a response back to the user i.e. when you encounter something like res.send(‘Hello World’);
let’s have a look at a very simple example.
app.get('/hello', function (req, res, next) {
res.send('USER')
})
Here we do not need next(), because resp.send will end the cycle and hand over the control back to the route middleware.
Now let’s take a look at another example.
app.get('/hello', function (req, res, next) {
res.send("Hello World !!!!");
});
app.get('/hello', function (req, res, next) {
res.send("Hello Planet !!!!");
});
Here we have 2 middleware functions for the same path. But you always gonna get the response from the first one. Because that is mounted first in the middleware stack and res.send will end the cycle.
But what if we always do not want the “Hello World !!!!” response back. For some conditions we may want the "Hello Planet !!!!" response. Let’s modify the above code and see what happens.
app.get('/hello', function (req, res, next) {
if(some condition){
next();
return;
}
res.send("Hello World !!!!");
});
app.get('/hello', function (req, res, next) {
res.send("Hello Planet !!!!");
});
What’s the next
doing here. And yes you might have gusses. It’s gonna skip the first middleware function if the condition is true and invoke the next middleware function and you will have the "Hello Planet !!!!"
response.
So, next pass the control to the next function in the middleware stack.
What if the first middleware function does not send back any response but do execute a piece of logic and then you get the response back from second middleware function.
Something like below:-
app.get('/hello', function (req, res, next) {
// Your piece of logic
next();
});
app.get('/hello', function (req, res, next) {
res.send("Hello !!!!");
});
In this case you need both the middleware functions to be invoked. So, the only way you reach the second middleware function is by calling next();
What if you do not make a call to next. Do not expect the second middleware function to get invoked automatically. After invoking the first function your request will be left hanging. The second function will never get invoked and you will not get back the response.