The Wayback Machine - https://web.archive.org/web/20240906212847/https://www.geeksforgeeks.org/how-to-exit-after-res-send-in-express-js/
Open In App

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

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

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 GeeksforGeeks” 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, GeeksforGeeks!');
    // 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:

Output1

Approach 2: Using res.end():

We are going to use res.end() function to exit after res.send() response is been done. This function is mainly used to end or terminate the repose process. This will terminate the process and will not pass the control to the next middleware or route. The request is been terminated.

Syntax:

// Inside a route handler
app.get('/', (req, res) => {
// Sending a response
res.send('Hello, World!');

// Exiting the application using res.end()
res.end();
});

Example: In the below example, we are sending the response with the res.send() function in the root route (‘/’). The middleware that is used to handle after res.send() is not executed because the res.end() stops the response process immediately.

JavaScript
// app.js
const express = require('express');
const app = express();

app.get('/', (req, res) => {
    // Sending a response
    res.send('Hello, Geeks!');
    // Exiting using res.end()
    res.end();
});
app.use((req, res, next) => {
    // Middleware to handle after res.send()
    console.log('After res.send(), exiting using res.end()');
});
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

Output:



Similar Reads

Difference between res.send() and res.json() in Express.js?
In this article, we will learn about res.send() & res.json(), along with discussing the significant distinction that differentiates between res.send() & res.json(). Let us first understand what is res.send() and res.json() in Express.js? res.send() - The res.send() function is used for sending the response for the HTTP request. It takes a p
3 min read
Difference between res.send() and res.json() in Express
res.send():res.send() is a method used to send a response back to the client. It's a versatile function that can handle various types of responses, such as HTML, plain text, or even binary data. When you use res.send(), Express automatically sets the appropriate Content-Type header based on the type of data you're sending. res.json():res.json() is
1 min read
Express res.send() Function
The res.send function is used to send a response in form of various types of data, such as strings, objects, arrays, or buffers, and automatically sets the appropriate Content-Type header based on the data type. res.send in ExpressThe res.send() function sends the HTTP response. The body parameter can be a String or a Buffer object or an object or
3 min read
Express.js res.location() Function
The res.location() function is used to set the response Location HTTP header to the path parameter which is being specified. Basically, it is used to set the response header. It doesn't end the response, after using it you can write a response body if you want to write. Syntax: res.location( path ) Parameter: path: It refers to the URL which is spe
2 min read
Express.js | res.format() Function
The res.format() function performs content negotiation on the Accept HTTP header on the request object if it is present. This function checks the Accept HTTP request header and then invokes the corresponding handler depending on the Accept value. Syntax: res.format(object) Installation of the express module: You can visit the link to Install the ex
2 min read
Express.js res.clearCookie() Function
The res.clearCookie() function is used to clear the cookie specified by name. This function is called for clearing the cookies which as already been set. For example, if a user cookie is set, then it can be cleared using this function. Syntax: res.clearCookie(name, [ options ]) Parameters: Name: It is the name of the cookie which is to be cleared.
2 min read
Express.js res.sendStatus() Function
The res.sendStatus() function is used to set the response HTTP status code to statusCode and send its string representation as the response body. Syntax: res.sendStatus( statusCode ) Parameter: The statusCode parameter describes the HTTP status code. Returns: It returns an Object. Installation of the express module: You can visit the link to Instal
2 min read
Express.js res.append() Function
The res.append() function appends the specified value to the HTTP response header field and if the header is not already set then it creates the header with the specified value. Syntax: res.append(field [, value]) Parameter: The field parameter describes the name of the field that need to be appended and the value parameter can be a string or an ar
2 min read
Express.js res.jsonp() Function
The res.jsonp() function is used to send a JSON response with JSONP support and this function is similar to the res.json() function except that it opts-in to the support of JSONP callback. Syntax: res.jsonp( [body] ) Parameter: The body parameter describes the body type which can be sent in response. Return Value: It returns an Object. Installation
2 min read
Express.js res.get() Function
The res.get() function returns the HTTP response header specified by the field. The match is case-insensitive. Syntax: res.get( field ) Parameter: The field parameter describes the name of the field. Return Value: It returns an Object. Installation of the express module: You can visit the link to Install the express module. You can install this pac
2 min read
Express.js res.links() Function
The res.links() function is used to join the links provided as properties of the parameter to populate the response’s Link HTTP header field. Syntax: res.links( links ) Parameter: The link parameter describes the name of the link to be joined. Return Value: It returns an Object. Installation of the express module: You can visit the link to Install
2 min read
Express.js res.attachment() Function
The res.attachment() function is used to set the HTTP response Content-Disposition header field to 'attachment'. If the name of the file is given as a filename, then it sets the Content-Type based on the extension name through the res.type() function and finally sets the Content-Disposition 'filename = ' parameter. Syntax: res.attachment( [filename
2 min read
Express.js res.vary() Function
The res.vary() function is used to add the field to the Vary response header, if it is not there already. The Vary header indicates which headers it’s basically used for content negotiation. Syntax: res.vary( field ) Parameter: The field parameter describes the name of the field. Return Value: It returns an Object. Installation of the express modul
2 min read
Express.js res.type() Function
The res.type() function is used to set the Content-Type HTTP header to the MIME type determined by the mime.lookup() function for the specified type. Syntax: res.type( type ) Parameters: The type parameter describes the MIME type. Return Value: It returns an Object. Installation of the express module: 1. You can visit the link to Install the expres
2 min read
Express.js res.set() Function
The res.set() function is used to set the response HTTP header field to value. To set multiple fields at once, pass an object as the parameter. Syntax: res.set(field [, value]) Parameters: The field parameter is the name of the field and the value parameter is the value assigned to the field parameter. Return Value: It returns an Object. Installati
2 min read
Express.js res.download() Function
The res.download() function transfers the file at the path as an 'attachment'. Typically, browsers will prompt the user to download. Syntax: res.download(path [, filename] [, options] [, fn]) Parameters: The filename is the name of the file which is to be downloaded as an attachment and fn is a callback function. Return Value: It does not return an
2 min read
Express.js res.headersSent Property
The res.headersSent property is a boolean property that indicates if the app sent HTTP headers for the response. Syntax: res.headersSent Parameter: No parameters. Return Value: This property returns a Boolean value either True or False. Installation of the express module: You can visit the link to Install the express module. You can install this pa
2 min read
Express.js res.app Property
The res.app property holds a reference to the instance of the Express application that is using the middleware. Syntax: res.app Parameter: No parameters. Return Value: Object Installation of the express module: You can visit the link to Install the express module. You can install this package by using this command. npm install express After install
2 min read
Express JS res.redirect() Function
The res.redirect() function redirects to the URL derived from the specified path, with specified status, an integer (positive) which corresponds to an HTTP status code. The default status is “302 Found”.  Syntax: res.redirect([status] path)Parameter: This function accepts two parameters as mentioned above and described below: status: This parameter
2 min read
Express res.json() Function
The res.json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.stringify() method. Syntax:   res.json( [body] )Parameters: The body parameter is the body that is to be sent in the response. Return Value: It returns an Object. Steps to Instal
2 min read
Express res.render() Function
The res.render() function in Express is used to render a view and sends the rendered HTML string to the client.  Syntax:  res.render(view [, locals] [, callback])Parameters: This function accepts two parameters as mentioned above and described below:   Locals: It is an object whose properties define local variables for the view.Callback It is a cal
2 min read
Express.js res.sendFile() Function
The res.sendFile() function transfers the file at the given path and it sets the Content-Type response HTTP header field based on the filename extension.  Syntax: res.sendFile(path [, options] [, fn])Parameter: The path parameter describes the path and the options parameter contains various properties like maxAge, root, etc and fn is the callback f
2 min read
Express res.status() Function
The res.status() function sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.  Syntax: res.status( code )Parameter: This function accepts a single parameter code that holds the HTTP status code.  Return Value: It returns an Object.  Steps to create the Express App and Installing the Modules:Step 1: Initiali
2 min read
Express res.cookie() Function
The res.cookie() function is used to set the cookie name to value. The value parameter may be a string or object converted to JSON. Syntax: res.cookie(name, value [, options])Parameters: The name parameter holds the name of the cookie and the value parameter is the value assigned to the cookie name. The options parameter contains various properties
2 min read
Express res.end() Function
The res.end() function concludes the response process and is derived from the HTTP.ServerResponse's response.end() method in the Node core. It is employed to promptly conclude the response without including any data. Syntax:  res.end([data] [, encoding])Parameters: The default encoding is 'utf8' and the data parameter is the data with which the use
2 min read
Express res.locals Property
The `res.locals` property is an object that holds response local variables specific to the current request. It has a scope limited to the request and is accessible only to the view(s) rendered during that particular request/response cycle, if any.  Syntax: res.localsParameter: No parameters.  Return Value: Object  Steps to Create the Application:St
2 min read
Express Returns Servers HTML Error Page Instead of res.json Error Message
When building APIs with Express.js, you might encounter a situation where instead of returning a JSON error message, your server returns an HTML error page. This can be frustrating, especially when your application relies on consistent JSON responses. In this article, we'll explore why this happens and how to ensure that Express.js returns a JSON e
4 min read
Explain the use of req and res objects in Express JS
Express JS is used to build RESTful APIs with Node.js. We have a 'req' (request) object in Express JS which is used to represent the incoming HTTP request that consists of data like parameters, query strings, and also the request body. Along with this, we have 'res' (response) which is used to send the HTTP response to the client which allows the m
4 min read
How to Send Email using 'git send-email' via Gmail?
Email communication is a crucial aspect of collaborative software development. Whether you're sharing patches, discussing issues, or coordinating with your team, knowing how to send emails directly from your Git repository can be highly efficient. In this article, we will guide you through the process of configuring and using git send-email with Gm
3 min read
How to Expire Session After 1 Min of Inactivity in express-session of Express.js ?
To automatically expire sessions after 1 minute of inactivity in an Express.js application using express-session, configure the session settings with the cookie.maxAge and implement session touch logic to track activity. ApproachTo expire the session after 1 min of inactivity in the express-session of Express.js we use expires: 60000 in the middlew
2 min read