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

143 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

  24. I’ve tried a few platforms lately, but the gameplay here is surprisingly smooth. The bonuses are actually fair and easy to claim. Highly recommend checking out mumu86slot for a great session.

  25. Top notch graphics and really engaging gameplay. It is honestly one of the best gaming experiences I have had in a long time. Big thanks to ck888game

  26. The slot games here are amazing and the jackpots are actually reachable. I had a great run yesterday on ph32jili.

  27. The slot variety is insane! I spent hours trying different games and they all look stunning. Big wins are actually possible at jilicashslot

  28. Super easy to get into the account and start playing. I like the layout and how easy it is to find the latest promotions. Check out jljl888login.

  29. This place has completely upgraded my weekend gaming routine. The graphics are stunning, the games load fast even on my older phone, and the VIP rewards actually mean something. I always feel welcome whenever I log in. Give it a try and you will understand why I keep coming back. x882

  30. I have been using this platform for a while now and the payouts are consistently fast. Definitely one of the most reliable sites I have encountered. Check out idrpvip5 if you want a premium feel.

  31. Really impressed with the bonus offers here. It feels like they actually care about the players. I am sticking with inyono7777 from now on.

  32. I have tried many different links for jili games but this one never disappoints me during peak hours. The connection stays strong and I can jump right into my favorite titles without any annoying delays. It feels like the developers really care about keeping things smooth for us players. You will notice the difference right away. 365jililink

  33. I’ve been playing here for a few weeks and the payouts are actually legit. Really smooth experience so far. Check out krcasinowinoui for a great time!

  34. Km888login – the login was quick, that’s always a win! I tested out a few of the slot games and had a decent run. I’d like to see some more payment options, though. Check it out yourself using this link: km888login

  35. I was looking for a reliable link and this one works perfectly. The site loads fast and the games are top-notch. Great experience overall with 7sjililink

  36. Finally found a site that doesn’t lag during big wins. The payouts are fair and the support team is quite helpful. Check out brlwinbr if you want a stable experience.

  37. Finding a trustworthy gateway for my favorite sports has been a hassle until I stumbled upon this page. Everything runs smoothly and the payment gateways are completely secure. I appreciate how transparent they are with terms and conditions. Great experience so far and counting on more mxgodmx

  38. I really appreciate the transparency and the quick payouts. It is hard to find a site that is this honest with its players these days. Great experience overall with 32reds

  39. I’ve tried a few sites recently but this one really stands out. The loading speed is great and the games are super smooth. Definitely check out idtopslot88 if you want a hassle-free experience.

  40. Finally a site that doesn’t lag during peak hours. The login process is quick and everything just works perfectly on my phone. I always use jili30login for my daily gaming sessions.

  41. So, I checked out 68wim. Everything goes ok so far and had some fun, so i recommend it. Do some research first! Check 68wim

  42. Honestly, the winning streaks I’ve had here are unbelievable. It is a legit platform and the withdrawal process is a breeze. Check out phjilibet88

  43. The bonuses here are legit and the registration process took me less than two minutes. Really impressed with the speed. iny7777

  44. I have tried many platforms but this one feels the most fair. The bonuses are actually usable and the wins feel real. Cheers to pk777as.

  45. Great bonuses for new members and the customer support is very responsive. Check out 888starzlogin if you want a reliable site.

  46. The VIP treatment here is actually real. I feel valued as a player and the exclusive perks are a nice touch. krvip is definitely the way to go.

  47. I was skeptical at first but the app performance is top notch. Smooth transitions and quick loading times. Highly recommend downloading bd2777bedapk if you want a hassle free experience.

  48. Really impressed with the game selection here. Everything loads quickly and the graphics are crisp. 98pakgame is definitely a hidden gem.

  49. The login process is quick and secure which is exactly what I need. No more endless loading screens, just straight to the action with tp999login.

  50. If you love Jili slots, this is the spot. The jackpot feels reachable and the loading speed is impressive. Check abjilislot

  51. I love the daily bonuses and the competitive odds. It keeps the game exciting every single time I log in. See you at aa44bet.

  52. Navigating this site feels like a breath of fresh air compared to the cluttered interfaces I usually deal with. Everything is organized neatly and I found my favorite table games within seconds. The welcome package actually matches the terms and the wagering requirements are fair for casual players. Smooth sailing all the way. npkhalti88

  53. The graphics are top notch and the gameplay is very addictive. I’ve had some decent wins here already. Check out pkjk777 for yourself.

  54. Honestly, managing the kids makes finding time for this tough, but the variety at Queen Casino looks great. I need something quick after dropping them off. Check out queen king download for some slots; it seems straightforward enough for a tired parent!

  55. Really impressed with the transparency and the fair play here. It feels like a community where players are actually valued. I am sticking with vnua88 from now on.

  56. The registration was so quick and the welcome bonus is actually generous. I am really enjoying the slot variety here. Definitely visit 55vip777loginregister to get started.

  57. Downloading the app took literally two minutes and it runs perfectly on my older phone. The push notifications keep me in the loop for major matches and the odds are consistently competitive. I tell all my friends about tk9991app whenever they ask for recommendations.

  58. The focus on ‘simple fun’ is key; it mitigates cognitive load. Keep the UX smooth, otherwise, the inherent dopamine loop falters. Check out jljl55 club app for a good feel.

  59. I love the lottery style games here. It is a great way to unwind after work and maybe win something big. brlottus is my go-to site now.

  60. The login process is seamless and I love the bonuses they offer for new users. If you are looking for a little excitement, check out spintimephlogin.

  61. The emphasis on a clear user flow is key; it mirrors how one analyzes any system. For deeper insights into similar platforms, check 79p download apk. Great breakdown!

  62. Love the vibe here! It feels like a real community and the live dealer games are super engaging. Give swerte999live a try

  63. Solid platform with a very user friendly layout. I appreciate how easy it is to manage my funds. idnaga169 is definitely my new go to site.

  64. Middleware structure is fundamental for building resilient, high-throughput systems. The focus on logging and error handling highlights that reliability isn’t just code; it’s a business requirement. Maintaining this level of robust backend stability is crucial, whether powering a complex API or ensuring a platform like okfan legit offers seamless user experience.

  65. Best online casino experience in the Philippines so far. The customer support is very responsive and helpful with my deposit. Love phcash11casino.

  66. I hit a decent streak here last night! The slots are exciting and the graphics are top notch. If you love spinning the reels, ph7spins is the place to be.

  67. Really impressed with the security and the way they handle transactions. It feels very safe to play here. Visit ph788ph

  68. I’ve been trying out a few sites lately and this one really stands out. The interface is smooth and the payouts are fast. Definitely worth a try if you want a reliable experience. Check out idmambawin for more.

  69. Solid platform with a great community. I like how they keep adding new games every month to keep things exciting. Check out vnfy88.

  70. Downloading the app was so simple and now I can place my bets anytime without waiting. The live match tracking is top notch and keeps me fully engaged all game long. Come try 1xbetecuadordescargar for yourself

  71. I’ve been using this platform for a while now and the interface is super smooth. Definitely one of the best options available right now. Check out krbetwinnerapp for a great experience.

  72. Best place for those who love high stakes and big wins. The graphics are amazing and the vibe is just right. Go visit buaya777 now.

  73. The slots here are incredibly exciting and the graphics are amazing. I am winning big at megawinsslot

  74. Really enjoying the vibe here. Everything is easy to navigate and the customer support is actually helpful. Highly recommend 56wgame for anyone starting out.

  75. The slots here are so addictive and the graphics are top notch. I hit a decent jackpot last night! You guys should try sinar777slot right now.

  76. Hmm, cái cách họ phân tích RTP và độ biến động ở 123b 03 hay thật. Giúp mình xem xét kỹ hơn phần quản lý vốn theo khung dữ liệu đó được không nhỉ? 🤔

  77. The bonus system on xlxwinplataforma is quite generous compared to other sites I’ve used. It really helps when you are just starting out. Definitely worth checking out. xlxwinplataforma

  78. Finally found a platform that doesn’t lag during peak hours. The game variety here is top notch. Highly recommend bddb89 for anyone looking for a bit of fun.

  79. Smart players prioritize quick, verified platforms – Casino Plus PH’s fast account setup (under 30 secs!) is a huge plus. Considering trying their slots – check out the casino plus ph apk – convenient payment options are key for me!

  80. The mobile experience is just perfect. I can play anywhere and anytime without any glitches. 4444winapp is a total game changer.

  81. Best slot games I have found in the Philippines recently. The interface is very friendly for mobile users. Love phjilibet019!

  82. This is hands down the number one platform for me. Everything from the deposits to the gameplay is top notch. Visit phno1jili and see for yourself.

  83. The gameplay is addictive and the graphics are top notch. It is honestly one of the most stable platforms I have used in a long time. Five stars from me. pkzh888game

  84. Everything from the signup to the first win was seamless. The community here is great and the platform is very stable. Big thanks to pharionph.

  85. Found this site through a friend and it has been a blast so far. The game selection is top notch. Try ph62ph.

  86. That level design was chef’s kiss! Seriously immersive. Thinking about trying some online casino games too – heard good things about the rewards on cc6ph8 games, especially with that easy registration process! Fun times ahead.

  87. Finally found a place that doesn’t lag during the peak hours. The graphics are crisp and the bonus offers are actually fair. Love it 1444casino

  88. Hmm, I was skeptical about the ‘luck’ angle here. The deep dive into RTP vs. house edge actually clarified things-it’s more math than magic! Check out swerte99 app casino for a real look at structure.

  89. Just had an amazing run here last night. The variety of games is insane and the support team is very helpful. braffun is where the real fun is at.

  90. The bonuses here are genuinely generous compared to other sites I have used. It feels like they actually care about their players. Love php63ph.

  91. Super easy to navigate and the deposit options are very flexible. It’s refreshing to find a site that focuses on the player experience. br56b

  92. I have tried quite a few betting platforms but trzirvebet stands out for its clean layout and fair odds across the board. Deposits process smoothly and customer service responds within minutes whenever I have a quick question. Highly recommend giving it a shot. trzirvebet

  93. Finally found a site that actually cares about its users. The customer support team is super helpful and the bonuses are actually worth it. Love krktwin33 so far.

  94. Yo, 79mgame! I’ve been hitting this site up for a while now. Pretty solid selection, keeps me coming back. Check it out, 79mgame, you might dig it.

  95. Honestly the best experience I have had with slots recently. The payouts are fair and the interface is super smooth. Check out phggjili for a great time.

  96. I was struggling to find a reliable spot until I tried this. The interface is super smooth and easy to navigate. Glad I found rotowirelogin.

  97. Best gaming experience I have had in a while. The variety of games is insane and everything loads quickly. Love playing on zk888game.

  98. Finally found a platform that doesn’t lag during peak hours. The game variety is impressive and I had a great run last night. Give pkluckywingame a shot!

  99. The user experience is top notch and the rewards are generous. I’ve shared this with my friends and we are all having a blast on 777zkapk.

  100. Best betting experience I’ve had in a while. The odds are competitive and the customer support team is actually helpful. Definitely sticking with br76xbet from now on.

  101. I’ve been looking for a reliable place to play and this one really hits the spot. The interface is super smooth and the payouts are fair. Definitely check out pk939game if you want a great experience.

  102. Hmm, গেমের র্যাঙ্ক রেট তো বুঝলাম, তবে প্ল্যাটফর্মের ডেটা যাচাই করাটা জরুরি। শুধু নাম দেখে বিশ্বাস করা ঠিক না। 6667 bd login এর মতো জায়গায় সব শর্তপত্র ভালো করে দেখে নিতে হয়।

  103. Finally found a site that actually cares about its users. The customer support team is super helpful and the bonuses are actually worth it. Love krktwin33 so far.

  104. Really enjoying my time here with such a wide variety of games to choose from. The registration process was quick and the welcome offer gave me a great start. Transactions are secure and I never worry about my funds. Highly recommend this site to all my friends. mc88kjcvn

  105. The game selection is massive and the community vibes are great. I’ve met some cool people while playing here. Check out rs789game for some action.

  106. The app is super stable and loads quickly. No lags or crashes which is exactly what I need when playing. Love the setup at x111gameloginapk.

  107. I’ve been playing here for a few weeks now and the payout speed is impressive. Definitely one of the most reliable platforms I’ve found lately. Check out brzzwinvip for a great experience.

  108. I’ve been trying a few different spots lately and this one really stands out. The interface is smooth and the payouts are quick. Definitely check out br234bet if you want a reliable experience.

  109. The welcome bonus here is honestly the best I have seen this year. I love how smooth the mobile version runs and the slot collection is top notch. Every spin feels fair and the payouts are consistent. You should check out 65jili

  110. The user experience is top notch and the rewards are generous. I’ve shared this with my friends and we are all having a blast on 777zkapk.

  111. I’ve been playing here for a few weeks now and the payout speed is honestly impressive. Highly recommend vne888 for anyone looking for a reliable spot.

  112. Honestly the best experience I’ve had recently. The layout is intuitive and the content is top notch. Keep up the great work guys! phpub7774

  113. I’ve been playing here for a few weeks and the payout is surprisingly fast. Definitely one of the smoothest experiences I’ve had lately. Check out krphlwin for a great time!

  114. Great selection of games and the promotions are actually useful. It is my go-to spot for some weekend fun. Try 291jiliph if you want a reliable site.

  115. Best gaming experience in the region so far. The local payment methods make it so much easier to deposit and play at manilaplayasia.

  116. Best slot experience I have had in a long time. The graphics are crisp and the wins feel rewarding. Check it out at jk777game.

  117. pkgb777 is a gem. I appreciate how transparent they are with their rules and promotions. It makes the whole gaming experience much more relaxing and trustworthy.

  118. Found this place through a friend and it did not disappoint. The bonuses are actually useful and not just marketing fluff. Love playing at bdok777bet

  119. I’ve been trying a few sites lately and this one is actually smooth. The payouts are fast and the interface is very user friendly. Definitely recommend ph10jilicc to anyone looking for a reliable spot.

  120. The login process is seamless and I had no issues setting up my account. It feels very secure and professional. I prefer using 20jililogin for my daily gaming.

  121. The app version is just perfect. I can play anywhere and the rewards keep coming in. Download jiligemsapp and see for yourself.

  122. A very friendly community and a fair gaming environment. I’ve shared this with a few friends and we are all enjoying the experience. ph29ph

  123. The login process is super quick and I had no issues setting up my account. Everything feels very professional and secure. Give it a go at jilibet020comloginregister

  124. Really impressed with the game variety here. I had a great run last night and the support team was helpful. Highly recommend vn188beet for anyone looking for action.

  125. If you are looking for a fair and honest gaming site, phjilibett is the way to go. Five stars from me!

  126. The rewards here are insane compared to other places I’ve tried. Really feeling the luck on this site lately ph777bar

  127. The VIP perks are actually worth it. I feel like a high roller even with modest bets. If you want a premium feel then cassinovip222 is where it is at.

  128. Just a heads-up about ph987comlogin: it’s decent. The UI is a little dated, but hey, if it ain’t broke, don’t fix it, right?

  129. The login process is seamless and the mobile version works like a charm. No glitches so far. Big thanks to 7gbetlogin for the great service.

  130. No more hassle with account access! The login page is stable and works perfectly on my mobile. Cheers to 8jilibetlogin.

  131. Finally found a reliable place to get the apk. The loading speed is impressive and everything works perfectly. Highly recommend vnx888apk.

  132. Downloading the APK was super simple and the app runs perfectly on my phone without any lag. Love pkx111gameapk

  133. Finally found a login page that actually works without any glitches. The app is fast and the games load instantly. Highly recommend pwin777applogin for anyone tired of laggy sites.

  134. As someone who prefers using crypto, this site is a breath of fresh air. Transactions are instant and the privacy is great. kryptocasinokr is perfect for crypto users.

  135. Such a fun vibe and the games are incredibly addictive. I had a huge win yesterday and the withdrawal was processed in minutes. 777zcgame is legit.

  136. Fast withdrawals are a must for me, and this site delivers every single time. No stress at all with 11phcash.

  137. The login process is super smooth and I rarely encounter any glitches. It makes the whole gaming session much more enjoyable. Highly recommend 17jililogin to everyone.

  138. Really liking the variety of options here. It is easy to navigate and the customer support team is actually helpful and responsive. Five stars! 688jilicomlogin

  139. Really enjoying the current promotions. The community here is friendly and the games are addictive. See you all at vnfu88!

  140. Logging in is fast and the system is very stable. No more annoying crashes during the most exciting moments of the game! 203publogin

  141. Just found this legit Jilib site for real slots! The jilib download works perfectly on my phone now. Their support is actually helpful unlike other scams out there trying to rip us off today guys!

  142. I was skeptical at first but the withdrawals are fast and secure. This is a hidden gem of a site. Visit atom138adalah now.

  143. Vuaclubclub is where it’s at for a good time! The vibes are good, and who knows, you might just win big! Give it a shot vuaclubclub.

Leave a Reply

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