Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Exit Process in Node.js ?
Next article icon

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

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  • Approach 1: Using next():
  • Approach 2: Using res.end():

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:


Next Article
How to Exit Process in Node.js ?

G

gauravggeeksforgeeks
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Geeks Premier League
  • Express.js
  • Geeks Premier League 2023

Similar Reads

  • How to skip a middleware in Express.js ?
    If we want to skip a middleware we can pass parameters to the middleware function and decide based on that parameter which middleware to call and which middleware to not call. Prerequisite: express.js: To handle routing. Setting up environment and execution: Step 1: Initialize node project npm init
    1 min read
  • How to Manage Sessions and Cookies in Express JS?
    Express is a small framework that sits on top of NodeJS web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing. It adds helpful utilities to NodeJS HTTP objects, it helps the rendering of
    4 min read
  • Setting a Default route in Express.js
    What is a default route?As we know that in an express application, there are so many URLs and requests involved. It might be possible that the user hit a route which is not included in our express app. In that case, the user will get an error for handling these kinds of issues, we set a default rout
    2 min read
  • How to Redirect 404 errors to a page in Express.js ?
    Express Js is a web application framework based on Node.js web server functionality that helps us to create web servers with lesser complexity and in a well-organized manner. Express provides routing services that help us in creating application endpoints that respond based on the HTTP request metho
    3 min read
  • How to Exit Process in Node.js ?
    In this article, we will see how to exit in NodeJS application. There are different types of methods to exit in Nodejs application, here we have discussed the following four methods. Table of Content Using ctrl+C keyUsing process.exit() FunctionUsing process.exitCode variableUsing process.on() Funct
    3 min read
  • How to receive post parameter in Express.js ?
    Express is a small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing; it adds helpful utilities to Node.js’s HTTP objects; it facilitates the
    3 min read
  • How to handle sessions in Express ?
    ExpressJS is a small framework that works on top of Node web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing. It adds helpful utilities to Node HTTP objects and facilitates the render
    4 min read
  • How to create custom middleware in express ?
    Express.js is the most powerful framework of the node.js. Express.js is a routing and Middleware framework for handling the different routing of the webpage, and it works between the request and response cycle. Express.js use different kinds of middleware functions in order to complete the different
    2 min read
  • How to use the app object in Express ?
    In Node and Express, the app object has an important role as it is used to define routes and middleware, and handling HTTP requests and responses. In this article, we'll explore the various aspects of the `app` object and how it can be effectively used in Express applications. PrerequisitesNode.js a
    3 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 paramete
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences