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

23 responses to “Express.js Middleware Basics”

  1. The game selection here is top notch. I spent hours playing and didnt encounter any lags. Great job to the team! phghplay888

  2. Five stars for the customer service and the overall gameplay. It feels like a real casino experience from the comfort of my home. agilaplaycasino

  3. The best link for those who want a stable connection to their games. No more downtime for me. Simply amazing! merryphlink

  4. Really loving the variety of games here. I tried a few different slots last night and the payouts felt fair. It is great to find a platform that actually values its players. innetbetcasino

  5. Finally a site that doesn’t lag during big matches. The login process is seamless and the betting odds are very competitive. Check out mmrbetlogin

  6. Great experience so far. The customer support is very responsive and the deposit options are convenient. Highly recommend bangabetlogin

  7. That’s a great point about skill playing a role – it’s not just luck! Reminds me of ocean king jackpot jili app casino, where aiming actually matters. Interesting to see platforms catering to local payment options too, like GCash! 👍

  8. Yo, just tried out QH99casino and it’s pretty legit. Slots are fire and the payouts are decent. Definitely worth checking out if you’re looking for a new place to spin some reels. Check it out at qh99casino.

  9. 365ok looks like a decent platform for sports betting. Lots of events covered and the interface is clean. I’m gonna see if I can make some clever predictions. Worth a look at 365ok.

  10. Heard about vuagaazad and gave it a shot. The games are decent and it’s a fairly user-friendly platform. Might become a regular here! Give it a whirl. vuagaazad

  11. Honestly, that description of smooth sessions rings true! Just remember to check out Kuya King for everything-it seems super user-friendly for mobile play. 😉

  12. The UI flow feels intuitive; optimizing that game library experience is key. Checking out queen philippines vip shows great depth! Solid design choices really elevate the whole platform feel.

  13. Playing on this platform feels completely fair and transparent every single time. I appreciate how they handle every transaction quickly and keep the games running without a single glitch. It is refreshing to find a site that truly puts players first and listens to the community. fairplayph

  14. Sometimes you just need a straightforward platform and this one delivers exactly that. No confusing menus or hidden fees just a clean gaming experience with fair odds. I appreciated how quickly they processed my withdrawal request and kept me updated via email. Great for both new players and seasoned veterans looking for reliability. bigplcmrgerlgidld

  15. Living in the Philippines we always want something local and trustworthy. That is exactly what I found with these folks. They understand our vibe and keep things fair for everyone in the community. Come see for yourself phibet789

  16. Just finished my kid’s homework; finally found a calm place at 22bet online casino. The color-coded zones help me relax, and the amber sign-up beacon was easy to spot even with tired eyes.

  17. Love the atmosphere and the way the promotions are set up. It feels like they actually care about the players. xbajeecasino is top notch.

  18. The slot variety here is insane. I love how the games load quickly without any glitches. Definitely my new go-to place for some fun spins at brasil777slots.

  19. Dice games are surprisingly complex when you dig into the math! Seeing platforms like JLTT PH prioritize regulatory compliance – like KYC & data protection – is reassuring. Check out the jltt ph app download for a secure experience. It’s good to know they’re following strict guidelines!

  20. Really insightful breakdown of basic strategy! It’s cool to see a focus on responsible gaming too – platforms like yyy7 app seem to be prioritizing player well-being, which is a huge plus for newcomers like me. Learning to assess your habits before you play is smart!

  21. I have been playing here for a couple of months now and the withdrawal process is honestly the fastest I have come across. You can really tell they care about keeping things transparent for their community. Highly recommend giving it a spin if you want a stress free gaming session. rwintoday

  22. The customer service really stands out because they reply with actual answers instead of copy paste templates. I appreciate how secure the deposit page feels and how quickly my funds are ready to use. It is nice to find a place that takes the time to offer fair limits and genuine rewards for loyal players. I will definitely be returning for my weekend sessions. Come see for yourself at new88bicom.

  23. I have been playing online for years and this site finally made me feel like a VIP without spending a fortune. The withdrawal process is straightforward and I never had to wait more than a day to receive my winnings. Perfect for anyone who wants a relaxed and trustworthy gaming environment. artimba

Leave a Reply

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

汽水音乐mumu模拟器谷歌邮箱telegramtodesk易翻译