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

3 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

Leave a Reply

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