Skip to content

Express.js console.log every request header, body, and query string

Last updated on July 12, 2023

In an Express.js application, you can log every request’s headers, body, and query strings by creating a custom middleware function.

Here’s an example of how you can achieve this:

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

// Custom middleware function to log request details
function logRequest(req, res, next) {
  console.log('Request Headers:', req.headers);
  console.log('Request Body:', req.body);
  console.log('Query Strings:', req.query);
  next();
}

// Apply the middleware to log every request
app.use(logRequest);

// Your routes and other middleware...

// Start the server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In the code above, we define a custom middleware function called logRequest. This function logs the request headers, body, and query strings using console.log. After logging the details, the middleware calls the next() function to pass control to the next middleware or route handler.

The app.use(logRequest) line adds the logRequest middleware to the application, ensuring that it runs for every incoming request.

You can place this middleware at the desired location in your application’s middleware stack, depending on when you want the logging to occur. Remember to install the required dependencies (such as express if not already installed) and adjust the port number according to your needs.

With this setup, whenever a request is made to your Express.js server, the headers, body, and query strings of that request will be logged to the console.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments