Real-world mechanisms, state management, edge cases, performance trade-offs, and practical coding.
Answer: Express processes incoming HTTP requests using a linear queue-based pattern called the Middleware Pipeline.
next() to step to the next function.next():next() synchronously triggers the execution of the next middleware in line.next('route'), Express skips any remaining middleware functions in the current router stack and immediately jumps back to the main routing cycle.next(err)—meaning you pass any value inside next (except the string 'route')—Express skips all remaining normal middlewares and jumps straight into the Global Error Handling Middleware chain.next() but also send a response (e.g., res.send()), execution continues in the subsequent middleware. This often causes the notorious "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" crash.Answer: By default, Express intercepts sync runtime exceptions and passes them to its built-in error handler. For custom control, developers define custom error-handling middleware.
Why Exactly Four Arguments?
Express checks the length property (arity) of registered middleware functions using JavaScript's reflection features.
(req, res) or (req, res, next).(err, req, res, next).next argument (having only 3 arguments), Express will compile it as a regular middleware and completely fail to route active errors to it.Standard Template:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(err.statusCode || 500).json({
success: false,
message: err.message || 'Internal Server Error'
});
});
Answer:
express.Router is a mini-express application. It is used to isolate routes, handlers, and middlewares into independent, modular sub-sections of a system.
Benefits:
routes/users.js, routes/products.js, and routes/billing.js./api/v1 without manually attaching it to each endpoint.Example mount in primary entry file:
const billingRouter = require('./routes/billing');
app.use('/api/billing', billingRouter); // Isolates billing middlewares
Answer:
async route handler, the server will not pass the error to the global handler; instead, it raises an unhandledRejection event.app.get('/data', async (req, res, next) => {
try {
const data = await database.fetch();
res.json(data);
} catch (err) {
next(err); // Crucial step
}
});
next(err) behind the scenes.Answer: Battle-tested layout separates bootstrap from wiring:
src/
app.js # creates app, mounts middleware/routes (no listen)
server.js # listen + graceful shutdown + signal handling
routes/ # thin routers delegating to controllers
controllers/ # HTTP layer: validate, call services, shape responses
services/ # business logic (framework-free, unit-testable)
repositories/ # data access (knex/prisma/mongoose)
middlewares/ # auth, rate-limit, error, validation
config/ # env schema loading/validation
utils/
Key principles:
app without binding ports, and keeps lifecycle concerns isolated.modules/users/{routes,controller,service}) — pick one discipline and enforce with lint boundaries.You've completed the 5 free sample questions. Get unrestricted lifetime access to every question, model answer, implementation challenge, and all 27+ technologies for a single payment.
₹399 India / $9 International · One-time settlement · Zero subscription