skip to Main Content

I am working on Nodejs and using "Express js", Right now i am working on "middleware function", here is my current code

const express = require('express')
const app = express()

const myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}

app.use(myLogger)

app.get('/', (req, res) => {
  res.send('Hello World!')
})

I am confuse regaring "next" parameter,I have following question regarding middleware function

  1. what is use of "next" ? is this redirect to "next middlware function" ? if yes then how ?
  2. if there is not "second middleware" exist then what will happen ?
  3. if we not use "next" then what will happen ?
  4. can we redirect to custom middleware inside "next" ?

2

Answers


    1. Yes, The next parameter is used to pass control to the next middleware function in the chain. When you call next(), Express moves on to the next middleware function registered in the application. This allows you to create a sequence of middleware functions that are executed in order. If you omit next() or don’t call it, the request will be left hanging and the application will not move to the next middleware or the final request handler.

    2. If there is no second middleware function defined after app.use(myLogger), the application will move on to the final request handler, which is app.get('/', ...). The final request handler is responsible for sending the response back to the client. In your example, it sends the "Hello World!" response.

    3. If you don’t call next(), the application will hang and the subsequent middleware functions or the final request handler will not be executed. The request will not be completed, and the client will eventually time out or receive an error.

    4. Yes, you can redirect to a custom middleware function using next(). When next() is called with an argument (e.g., next('route')), Express skips the remaining middleware functions in the chain and moves to the next route handler. This can be useful for implementing conditional routing or skipping certain middleware functions based on specific conditions.

    Here’s an example of using next('route') to redirect to a custom middleware:

    const myMiddleware = function (req, res, next) {
      if (someCondition) {
        // Redirect to custom middleware
        next('route')
      } else {
        // Continue to the next middleware
        next()
      }
    }
    
    const customMiddleware = function (req, res, next) {
      // Custom middleware logic
    }
    
    app.use(myMiddleware)
    app.use(customMiddleware)
    
    app.get('/', (req, res) => {
      // Final request handler
    })
    
    
    Login or Signup to reply.
  1. Simply next() means continue with the first following path matching route. If you never call next() or response, the request will be stuck on that middleware. Middleware is there for 2 reasons: 1 manipulating data -you can add extra values into e.g. request.body for later uses- or if anything is unexpected you can respond without continuing to path matching routes.

    For example:

    // request sent to /users/user1
    
    const myLogger = function (request, res, next) {
        console.log('LOGGED')
        next()
    }
    
    router.use(myLogger);
    
    router.post('/users*', (request, res, next) => {
        if(!isAdmin(request)){
            return res.status(401).json();
        }
    
        return next();
    })
    
    router.post('/users/:id',(request, res, next) => {
        res.json(getUser())
    })
    
    function getUser(){
        return {name: 'Lorem', surname: 'Ipsum'}
    }
    
    function isAdmin(request){
        return true;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search