Control flow in express.js route – return vs next()

When working with routes, often two or more outcomes are wanted. This calls for controlling the flow of data when for instance sending and put request to the application.

In contrary to an “normal” application – one that runs offline, that doesn’t follow the request-response architecture – one would usually use “return” in order to tell the machine to stop the flow of a function, and return to the calling object. As an express.js app uses middleware, the route function cannot use “return”, but should rather use “next()” in order to pass the control flow on to the next middleware in line in order to process the request properly and return a proper response.

router.put('/:id', async (request, response) => {
    
    const id = parseInt(request.params.id)

    // check if given id is valid
    const { rows: budgets } = await pool.query(
        'SELECT * FROM budget WHERE id = $1',
        [id]
    )
    
    if (budgets.length === 0) {
        // no budgets was found with given id
        response.status(404).send('Invalid id')
        next()

    }

// budget returned = valid id
response.status(200).send(budgets);

Without calling “next()” in the if-block, the flow would continue after calling “response.status(404).send(‘Invalid id’)”. Using return, other middleware in line would be skipped. This could be middleware ensuring the security of the app, and therefore important not to skip.

Leave a comment