Express.js Middleware Basics

1. Logging Requests

Logging is one of the most common middleware tasks—it helps track incoming requests and responses.

Example:

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

// Custom logger middleware
app.use((req, res, next) => {
  const start = Date.now();
  console.log(`${req.method} ${req.url} at ${new Date().toISOString()}`);
  
  res.on('finish', () => {
    const duration = Date.now() - start;
    console.log(`${req.method} ${req.url} - ${res.statusCode} (${duration}ms)`);
  });
  
  next();
});

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

👉 Alternatively, you can use morgan, a popular logging middleware:

npm install morgan
const morgan = require('morgan');
app.use(morgan('dev'));

2. Error Handling

Express has built-in error handling middleware. Any middleware with 4 arguments (err, req, res, next) is treated as an error handler.

Example:

// Simulated error
app.get('/error', (req, res, next) => {
  const err = new Error('Something went wrong!');
  err.status = 500;
  next(err);
});

// Error-handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(err.status || 500).json({
    message: err.message || 'Internal Server Error',
  });
});

👉 Always place error handlers at the end of middleware stack.


3. Measuring Response Time

To measure how long each request takes, you can wrap timing logic in middleware.

Example:

app.use((req, res, next) => {
  const startHrTime = process.hrtime();

  res.on('finish', () => {
    const diff = process.hrtime(startHrTime);
    const time = diff[0] * 1e3 + diff[1] / 1e6; // in ms
    console.log(`Response time for ${req.method} ${req.url}: ${time.toFixed(2)}ms`);
  });

  next();
});

👉 Or use the response-time package:

npm install response-time
const responseTime = require('response-time');
app.use(responseTime());

Posted

in

by

Tags:

Comments

13 responses to “Express.js Middleware Basics”

  1. voslot Avatar

    Dice games are all about understanding probabilities – it’s fascinating! Seeing platforms like Voslot prioritize security with KYC is reassuring, especially when considering a voslot app download apk. Responsible gaming is key, and clear verification processes build trust. Great article!

  2. jili pg Avatar

    Solid article! Understanding stack sizes & position is key in tournaments. Thinking about quick registration like with a jili pg link can help focus on the game, not tech hurdles. Great read!

  3. winwinslot777 Avatar

    Hey y’all! If you’re a slot fan, Winwinslot777 is calling your name! Amazing payouts and a really cool theme. Check them out here: winwinslot777

  4. linkhello88discount Avatar

    Linkhello88discount is fire. Always find solid discounts. Great way to save while you play! Grab your discount here linkhello88discount.

  5. superlines casino Avatar

    Superlines Casino on okvip-new88 is the bomb. Games galore and payouts on point. Best casino I’ve found in ages! Try your luck here superlines casino.

  6. qq822 Avatar

    QQ822 is my go-to for quick scores. Easy to navigate and always something new to try. Get on it now qq822.

  7. jilibb Avatar

    Excellent overview of Express middleware! The logging and error handling patterns you’ve demonstrated are foundational for production applications. These techniques are especially crucial when building platforms where user session management and real-time monitoring are essential – much like the secure jilibb login systems we implement. Thanks for sharing these practical examples!

  8. 722betapp Avatar

    Gotta say, the 722betapp is actually pretty decent. Fast loading times and a clean interface. Makes placing bets on the go a breeze. Grab it here: 722betapp.

  9. 212betnet Avatar

    Hey, has anyone used 212betnet before? Looking for a new platform and their site looks slick. Let me know your thoughts. Check it out: 212betnet.

  10. ph364 Avatar

    Hey, just tried out PH364! Pretty cool site. Easy to navigate and found some interesting stuff. Definitely worth checking out. More options available at ph364

  11. lucky-bet Avatar

    Is lucky-bet a reputable site? Seen it mentioned with Luckybetbrasil.com a few times. Checking it out now: lucky-bet

  12. lotus 365 download Avatar

    Lotus 365 download? Got it right here! Quick and easy. Been playing all night. Thumbs up, guys! lotus 365 download

  13. golds bet apk download Avatar

    Looking for the Golds Bet APK download? Found it pretty easily and the install’s simple. Get it here golds bet apk download!

Leave a Reply

Your email address will not be published. Required fields are marked *