How to intercept response.send() / response.json() in Express JS
Last Updated :
26 Jul, 2024
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 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 javascri
5 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 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 provide
3 min read
How to resolve req.body is empty in posts error in Express? In Express the req.body is empty error poses a critical challenge in web development, particularly in the context of processing POST requests on the server side. This issue arises when the server encounters difficulties parsing the request body, resulting in an empty or undefined req.body object. De
4 min read
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. T
4 min read