Loading Depth Study
Preparing your workspace
Middleware functions run during the request-response cycle and can execute logic before the final route handler sends a response.
Middleware is one of the most important Express concepts. A middleware function receives req, res, and next. It can perform logging, authentication checks, validation, request parsing, or other shared logic. Calling next passes control to the next middleware or route handler. Middleware can be applied globally, to a router, or to specific routes. Error-handling middleware follows a special signature with four arguments.
An API can use one middleware for logging every request and another middleware to verify that the user is authenticated before accessing protected routes.
function logger(req, res, next) {
console.log(`${req.method} ${req.originalUrl}`);
next();
}
app.use(logger);
app.get('/courses', (req, res) => {
res.json({ message: 'Courses' });
});Every incoming request is logged before the request reaches its route handler.