Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
Node.js Core & Express Backend APIs 16 mins read Free Lesson

Express Middleware Pipeline & Error Handling

Author authentication middleware, request loggers, and centralized global error handling middleware.

Express Middleware Architecture

// Custom Request Logger Middleware
function requestLogger(req, res, next) {
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
    next(); // Pass control to next middleware in stack
}
app.use(requestLogger);

// Global Error Handling Middleware (4 arguments)
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(err.status || 500).json({
        error: err.message || 'Internal Server Error'
    });
});