Middleware and next() in Expressjs(Node)

Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

An Express application can use the following types of middleware:

  • Application-level middleware
  • Router-level middleware
  • Error-handling middleware
  • Built-in middleware
  • Third-party middleware

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD()(example:app.get(“/user”))

Example 1:

Invoke on all the requests.

var app = express()app.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})

Example 2:

Invoke on specific uri path:

Using use():

app.use('/user/:id', function (req, res, next) {
console.log('Request Type:', req.method)
next()
})

Using METHOD():

app.get('/user/:id', function (req, res, next) {
res.send('USER')
})

Example 3:

Invoke series of middleware functions on specific uri path:

app.use('/user/:id', function (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}, function (req, res, next) {
console.log('Request Type:', req.method)
next()
})

Example 4:

using next() with Route handlers.
Note: Route handlers enable you to define multiple routes for a path.

//Route 1
app.get('/user/:id', function (req, res, next) {
console.log('ID:', req.params.id)
next()
}, function (req, res, next) {
res.send('User Info')
})

// Route 2
app.get('/user/:id', function (req, res, next) {
res.end(req.params.id)
})

The second route will not cause any problems, but it will never get called because the first route ends the request-response cycle.

Example 5:

using next(‘route’) to skip middlewares and goto another Route

//Route 1
app.get('/user/:id', function (req, res, next) {
if (req.params.id === '0')
next('route')
else
next()
}, function (req, res, next) {
res.send('regular')
})

// Route 2
app.get('/user/:id', function (req, res, next) {
res.send('special')
})

To skip the rest of the middleware functions from a router middleware stack, call next('route') to pass control to the next route.
NOTE: next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD()functions.

Example 6:

using array in declaring middlewares

function logOriginalUrl (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}

function logMethod(req, res, next) {
console.log('Request Type:', req.method)
next()
}

var logStuff = [logOriginalUrl, logMethod]
app.get('/user/:id', logStuff, function (req, res, next) {
res.send('User Info')
})

Suffering from Knowledge Quest

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store