Approach 1 Using next()

We are going to use the next() function after calling the res.send(), this will allow the request to proceed to the next middleware or the route handler and indirectly exit the current function but further processing will be done in subsequent middleware or routes.

Syntax:

app.get('/example', (req, res, next) => {
// Tasks
// Sending response to the client
res.send('Response sent to the client.');
// Using next() to exit the handler and pass control to the next middleware or route handler
next();
});

Example: In the below example the application responds with “Hello w3wiki” when the request is made to the root route. After sending the response using res.send(), the middleware is executed and exits the application using next().

Javascript




// app.js
const express = require('express');
const app = express();
app.get('/', (req, res, next) => {
    // sending a response
    res.send('Hello, w3wiki!');
    // Exiting using next()
    next();
});
app.use((req, res, next) => {
    // middleware to handle after res.send()
    console.log('After res.send(), exiting using next()');
});
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});


Output:

How to Exit after res.send() in Express JS

In this article, we are going to learn how we can exit after the res.send() function in Express JS. In Express the res.send() method is mainly used to send a response to the client with the specified content. This function automatically sets the Content-Type Header which is based on the data provided.

We are going to implement the Exit after res.send() using below given two approaches.

Table of Content

  • Using next()
  • Using res.end()

Similar Reads

Approach 1: Using next():

We are going to use the next() function after calling the res.send(), this will allow the request to proceed to the next middleware or the route handler and indirectly exit the current function but further processing will be done in subsequent middleware or routes....

Approach 2: Using res.end():

...