Open In App

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

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

ezgifcom-crop-(2)

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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads