The Wayback Machine - https://web.archive.org/web/20240814104603/https://www.geeksforgeeks.org/how-to-intercept-response-send-response-json-in-express-js/
Open In App

How to intercept response.send() / response.json() in Express JS

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

In the context of Express , “intercept” usually refers to the process of capturing or modifying a request or response in a middleware function before it reaches its final destination (e.g., a route handler) or before it is sent back to the client.

In Express, intercepting response.send() or response.json() can be achieved by using middleware functions. Middleware functions in Express have access to the request, response, and the next middleware function in the application’s request-response cycle. We can use this feature to intercept and modify the response before it is sent to the client.

Prerequisites:

Approach to intercept responses in Express:

  • Middleware is used to override res.send() and res.json().
  • The overridden functions log the response body and then call the original functions.
  • Middleware is registered in the order it should be executed.
  • Route handlers trigger the intercepted functions when sending responses.

Syntax:

// Custom middleware to intercept all requests
app.use((req, res, next) => {
// Modify the response body or perform any other actions
console.log(`Intercepted request: ${req.method} ${req.url}`);
next();
});

Steps to Create Express application:

Step 1: In the first step, we will create the new folder by using the below command in the VScode terminal.

mkdir folder-name
cd folder-name

Step 2: After creating the folder, initialize the NPM using the below command. Using this the package.json file will be created.

npm init -y

Step 3: Now, we will install the express dependency for our project using the below command.

npm i express ejs

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.18.2"
}

Example: Implementation of above approach.

JavaScript
// server.js

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

// middleware to intercept response.send()
app.use((req, res, next) => {
    // Storing the original send function
    const originalSend = res.send;

    // Override function
    res.send = function (body) {
        // Modify the response body
        const Modifybody = "modified: " + body;

        console.log('Intercepted response.send():', body);
        console.log('Intercepted response.send():', Modifybody);
        // Calling the original send function
        originalSend.call(this, Modifybody);
    };
    next();
});

//middleware to intercept response.json()
app.use((req, res, next) => {
    const originalJson = res.json;

    // Override the json function
    res.json = function (body) {
        // Modify the response body
        const ModifybodyJson = { ...body, data: 'modified' }
        console.log('Intercepted response.json():', body);
        console.log('Intercepted response.json():', ModifybodyJson);

        originalJson.call(this, ModifybodyJson);
    };

    next();
});

// For /
app.get('/', (req, res) => {
    res.send('Hello, how are you?');
});

// For /json
app.get('/json', (req, res) => {
    res.json({ message: 'Hello, JSON!' });
});

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server at http://localhost:${PORT}`);
});

Output:

Uses of intercepting response in Express:

  • Logging: Capture and log details about incoming requests and outgoing responses for debugging and monitoring purposes.
  • Authentication/Authorization: Verify user identity or permissions before allowing access to certain routes.
  • Request/Response Modification: Modify requests or responses based on specific requirements or business logic.
  • Data Parsing/Transformation: Modify request or response bodies, parse incoming data, or transform it as needed.
  • Error Handling: Intercept errors and handle them centrally, providing consistent error responses.
  • Security Measures: Implement security measures such as setting HTTP headers for preventing attacks.
  • Middleware Organization: Use middleware to organize and modularize code, promoting reusability and maintainability.


Similar Reads

How to Send Response From Server to Client using Node.js and Express.js ?
In web development, sending responses from the server to the client is a fundamental aspect of building interactive and dynamic applications. Express.js, a popular framework for Node.js, simplifies this process, making it easy to send various types of responses such as HTML, JSON, files, and more. This article will guide you through the process of
4 min read
How to send PDF in express route response and force browser download ?
In this article, we will see how to send PDF files in the express route's response and make the browser force download the file. Approach: Load required packages, then create an express app.Define the routes for homepage and PDF download requests.Create an index.html file with a single button to download PDF.Execute ajax call on button click to GET
4 min read
How to Send JSON Response using Node.js ?
NodeJS is the runtime environment, which can execute the javascript code on any platform. It is widely used to create and run web application servers because of its salient features. During production, several times we need to send the resources or some type of information as a response, and javascript object notation (JSON) syntax is widely used t
5 min read
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
How to Write Postman Test to Compare the Response JSON against another JSON?
In the era of API-driven development, testing the API responses to ensure their correctness is of paramount importance. One such test includes comparing the JSON response of an API against a predefined JSON. In this article, we will delve into how to write a Postman test for this purpose. Table of Content What is Postman?JSON and its Role in APIsWh
4 min read
Express JS express.json() Function
The express.json() function is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser. It’s a critical component for handling JSON data in RESTful APIs and web applications, allowing the server to automatically parse JSON data from the request body. Syntax:express.json( [options] )Param
3 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 send HTTP response code in PHP?
HTTP Response code: There are three approaches to accomplish the above requirement, depending on the version. For PHP versions 4.0: In order to send the HTTP response code, we need to assemble the response code. To achieve this, use header() function. The header() function contains a special use-case which can detect a HTTP response line and replac
2 min read
How to send REST response to html in Angular ?
In this article, we will see how to send API responses using HttpClient Module to an HTML using Angular, along with understanding the basic implementation through the examples. Angular is a JavaScript framework through which we can create reactive single-page web applications. For implementation, we are using the latest version of Angular (Angular
3 min read
How to resolve Postman unable to send request body to express application error ?
Encountering difficulties when attempting to send a request body from Postman to your Express application can be a frustrating experience. This issue may manifest in various ways, such as empty request bodies or unexpected behavior on the server side. In this troubleshooting guide, we will explore different approaches to resolve this problem and en
4 min read
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.se
3 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
How to send a JSON object to a server using Javascript?
JavaScript Object Notation (JSON). It is a lightweight data transferring format. It is very easy to understand by human as well as machine. It is commonly used to send data from or to server. Nowadays it is widely used in API integration because of its advantages and simplicity.In this example we are going to use AJAX (Asynchronous JavaScript And X
2 min read
How to Generate/Send JSON Data at the Client Side ?
Javascript Object Notation (JSON) is a widely used format for sending and receiving data to or from the server. In this article, we will use fetch API to send and receive data from the NodeJS server. Advantages of JSON: Because of its easy and small syntax, it executes the response in a faster way.It is supported by a wide range of browsers.Parsing
3 min read
How to Generate or Send JSON Data at the Server Side using Node.js ?
In modern web development, JSON (JavaScript Object Notation) is the most commonly used format for data exchange between a server and a client. Node.js, with its powerful runtime and extensive ecosystem, provides robust tools for generating and sending JSON data on the server side. This guide will walk you through the process of generating and sendi
3 min read
SVG intercept Attribute
The intercept attribute is used to specify the intercept of the color component's linear function. It should be noted that the type attribute is set to linear. The elements that are using this attribute includes: <feFuncA>, <feFuncB>, <feFuncG>, and <feFuncR>. Syntax: intercept = "number" Attribute Values: The intercept attr
2 min read
How to intercept all errors in a class instance ?
In this article, we will try to understand how we could easily intercept or catch all the errors in a class instance with the help of theoretical explanations as well as coding examples in JavaScript. Let us first understand the below section shows several syntaxes which we will use in order to solve our problem: Syntax: class Class_name { ... } An
4 min read
How to Intercept HTTP requests in web extension ?
In this article, we will understand to intercept the HTTP requests made by the browser using web extension API. What is Intercepting HTTP Request? Intercepting HTTP Requests means manipulating the HTTP requests made by the browser through the user or through asynchronous event handlers. With the help of web extension API, you can intercept any kind
3 min read
Express.js Response Complete Reference
Express.js is a small framework that works on top of Node.js 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. Express.js Response Properties:Properties Description Express.js res.app Property The res.app property holds a reference
4 min read
Express JS Response Timeout
In web development, it is very crucial to get timely responses to client requests. However, in some cases, servers might encounter prolonged processing times or server is not responding for a long duration. This type of timeout is called response timeout. Express JS offers a mechanism to handle response timeouts, which prevents indefinitely pending
2 min read
Properties and Methods of Request and Response Objects in Express
Request and Response objects both are the callback function parameters and are used for Express and Node. You can get the request query, params, body, headers, and cookies. It can overwrite any value or anything there. However, overwriting headers or cookies will not affect the output back to the browser. The following are the topics to be covered:
4 min read
How to manipulate cookies by using ‘Response.cookie()’ in Express?
Cookies are small data that is stored on the client's computer. Using this cookie various tasks like authentication, session management, etc can be done. In Express JS we can use the cookie-parser middleware to manage the cookies in the application. In this article, we going to manipulate cookies in Express JS by using the two scenarios/approaches
3 min read
How to set response header on Express JS assets?
In Express.js applications, we can set the response headers on assets to improve performance and also control the cache behavior. In this article, we will set the response header on Express.js assets by using 2 different approaches. We will see the practical implementation of this approach in terms of examples and output. The following approaches w
3 min read
Google Geo-coding Web Service (JSON response)
Prerequisite : JSON Formatting in Python Google has an excellent web service that allows us to make use of their large database of geographic information. Here, we are going to be working with the Google Maps API. In the old days, this Maps API was free and did 2, 500 requests per day but now they've made it so that parts of it are behind API keys
4 min read
How to return a JSON response from a Flask API ?
Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask. Prerequisites: Introduction to REST API What is a REST API? REST stands for Representational State Transfer and is an architectural sty
3 min read
How to get JSON response in Ajax ?
AJAX is a set of technologies that allows users to fetch data asynchronously without interfering with the existing page. We can fetch various types of data using AJAX like JSON, XML, HTML, and text files. In this article, we will see how to get JSON response in Ajax. Approach: To solve this problem, we will first consider a JSON file named "capital
4 min read
How to convert camel case to snake case in JSON response implicitly using Node.js ?
Camel case and snake case are two common conventions for naming variables and properties in programming languages. In camel case, compound words are written with the first word in lowercase and the subsequent words capitalized, with no spaces or underscore between them. For example, firstName is written in camel case. In snake case, compound words
5 min read
How to read Array of Nested JSON Response in Postman ?
We know that the postman is the one who delivers the letters sent by your friends, colleagues, or relatives and acts as a bridge of communication. Here Postman refers to the development of API that acts as a bridge or communication between different programs. In other words, it is an API client, made for developing, testing, and management. You can
3 min read
How to Check if the Response of a Fetch is a JSON Object in JavaScript?
In JavaScript, when making HTTP requests using the Fetch API, it's common to expect JSON data as a response from the server. However, before working with the response data, it's essential to verify whether it is indeed a JSON object or not. The below approaches can help you to check if the response is in JSON format or not: Table of Content By usin
2 min read
three90RightbarBannerImg