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

9 responses to “Express.js Middleware Basics”

  1. taihq88 Avatar

    Taihq88, decent platform, especially if you’re just starting out. Not too overwhelming and the options are clear. Recommend for beginners. Explore taihq88, it’s beginner friendly.

  2. hipsph88 Avatar

    Hipsph88, looking for something new, stumbled on this. So far, so good! Pretty interesting layout and some different features. Check out what hipsph88 has to offer.

  3. mcw1188 Avatar

    Mcw1188, been playing on here for a bit. It’s alright, nothing amazing but reliable. Solid platform for some casual fun, in my opinion. Give me a try, hit up mcw1188.

  4. jljl11 Avatar

    Solid middleware breakdown! Response time monitoring is crucial for real-time platforms like jljl11 online casino where millisecond delays affect user engagement. Thanks for sharing these practical patterns!

  5. matpet Avatar

    I think you might have meant Matbet? If so, check them out for streaming and sports action. : matpet

  6. matbet izle Avatar

    Just wanna chill and watch some games? Matbet makes it really easy to do. Give it a try! matbet izle

  7. nesine altılı Avatar

    Altılı betting made easy with Nesine. The platform is super user-friendly. Try it out: nesine altılı

  8. jl boss Avatar

    Smart bankroll management is key with any online gaming, and platforms like jl boss offer lots of options. Remember to set limits & play responsibly – it’s about fun, not just chasing wins! Exploring different games is great, too.

  9. 7spins Avatar

    Fascinating to see how gambling evolved – from simple dice games to today’s sophisticated online platforms! The “777” symbolism at 7spins slot really taps into that classic jackpot desire. Modern KYC processes, like those at 7Spins, are crucial for trust, too.

Leave a Reply

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