next()
is a middleware function in the application’s request-response cycle. You must call next()
to pass control to the next middleware function. Otherwise, the request will be left hanging.
res.json(), res.send()
is a express function used to send response to the client application . In other words it used this functions used to build your HTTP Reponse.
return
keyword returns from your function, thus ending its execution. This means that any lines of code after it will not be executed.
Note : Both next()
and res.send()
will not end your function from execution. Where adding a return
will stop function execution after triggering the callback.
Use return
is to ensure that the execution stops after triggering the callback. In some circumstances, you may want to use res.send
and then do other stuff.
Example :
app.use((req, res, next) => {
console.log('This is a middleware')
next()
console.log('This is first-half middleware')
})
app.use((req, res, next) => {
console.log('This is second middleware')
next()
})
app.use((req, res, next) => {
console.log('This is third middleware')
next()
})
Your output will be:
This is a middleware
This is second middleware
This is third middleware
This is first-half middleware
That is, it runs the code below next()
after all middleware function finished.
However, if you use return next()
, it will jump out the callback immediately and the code below return next()
in the callback will be unreachable.