QA
Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

❓ Interview Prompt: 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:

1
'req': The HTTP request object (headers, query params, body, URL).
2
'res': The HTTP response object (used to send JSON, HTML, headers, status codes).
3
'next': A callback function that passes control to the next middleware in the pipeline.

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!

Code Implementation Example

javascript
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'));
💡Express middleware pipeline execution order with authentication guard.
🎯 Interview Key Takeaway

Middleware functions execute sequentially. Every middleware must either terminate the request with res.send/json or call next().

#Express#Middleware#Routing#Beginner
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?

Beginner LevelExpress JS

How does Express error-handling middleware work and why does it require 4 arguments?