1. What is Express.js and how does the middleware pipeline work?
❓ Context: Explain Express routing, the request-response lifecycle, and how middleware functions process requests sequentially.
Express.js is a minimal, fast, and unopinionated web framework for Node.js. It simplifies building HTTP servers and RESTful APIs by providing a structured routing system and a Middleware Pipeline.
How Middleware Works:
A middleware function is a function that has access to three objects:
Sequential Execution:
When a request arrives at the server, Express passes it through the stack of registered middleware in the exact order they were declared with 'app.use()' or route handlers. If a middleware does not terminate the request-response cycle by sending a response (like 'res.json()' or 'res.send()'), it must call 'next()'. If it forgets to call 'next()', the request will hang indefinitely until the client times out!
import express from 'express';
const app = express();
// 1. Global Middleware (runs on every request)
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next(); // Pass control to the next middleware!
});
// 2. Built-in Middleware for parsing JSON bodies
app.use(express.json());
// 3. Route-specific Middleware + Final Route Handler
const checkAuth = (req, res, next) => {
if (req.headers.authorization === 'Bearer secret-token') {
next(); // Authorized! Proceed to handler
} else {
res.status(401).json({ error: 'Unauthorized access' }); // Terminate pipeline
}
};
app.get('/api/profile', checkAuth, (req, res) => {
res.json({ user: 'Alice', role: 'admin' });
});
app.listen(3000, () => console.log('Server running on port 3000'));Middleware functions execute sequentially. Every middleware must either terminate the request with res.send/json or call next().