Shoulder.dev Logo Shoulder.dev

Implementing Middleware in benhall/express-demo

Scenario:

You want to add middleware to your Express application to log each incoming request with the current timestamp.

Solution:

  1. First, let’s create a new file named middleware.js in the routes directory.
  2. In the middleware.js file, write the following code:
const morgan = require('morgan');

module.exports = function requestLogger(req, res, next) {
const logEntry = `[${new Date().toISOString()}] ${req.method} ${req.url}`;
console.log(logEntry);
next();
};
  1. Import the new middleware in app.js:
const requestLogger = require('./routes/middleware');
  1. Use the middleware in the app.js file:
app.use(requestLogger);
  1. Now, the incoming requests will be logged with the current timestamp before being processed by any other middleware or routes.

Tests:

  1. Start the application by running npm start in the terminal.
  2. Use a tool like Postman or curl to send requests to the application.
  3. Check the console output for the logged requests.

Expected Output:

[2023-03-28T14:30:12.000Z] GET /
[2023-03-28T14:30:12.001Z] GET /favicon.ico
[2023-03-28T14:30:12.002Z] GET /stylesheets/style.css

These tests should verify that the custom middleware is correctly logging incoming requests with the current timestamp.