Episode 3 — NodeJS MongoDB Backend Architecture / 3.6 — Middleware in Express

3.6 — Exercise Questions: Middleware in Express

Practice questions for all six subtopics in Section 3.6. Short-answer, prediction, and coding tasks. Try each without reopening the lesson files first.

How to use this material (instructions)

  1. Read lessons in order -- README.md, then 3.6.a through 3.6.f.
  2. Answer closed-book first -- write bullets or a few lines, then compare to the lesson.
  3. Code in a real project -- create a Node.js project, npm init -y && npm install express, and test middleware.
  4. Interview prep -- pair with 3.6-Interview-Questions.md.
  5. Quick review -- 3.6-Quick-Revision.md.

3.6.a — Understanding Middleware (Q1--Q8)

Q1. What are the three parameters that every Express middleware function receives? Describe what each one is for.

Q2. What happens if a middleware function calls neither next() nor sends a response? What does the client experience?

Q3. Write a minimal middleware function that logs the HTTP method and URL of every request, then passes control to the next middleware.

Q4. True or false: Route handlers in Express are technically middleware functions. Explain your answer.

Q5. Predict the console output when a GET / request is made:

app.use((req, res, next) => { console.log('A'); next(); });
app.use((req, res, next) => { console.log('B'); next(); });
app.get('/', (req, res) => { console.log('C'); res.send('OK'); });
app.use((req, res, next) => { console.log('D'); next(); });

Q6. Why does the order in which you register middleware with app.use() matter? Give a concrete example of a bug caused by incorrect order.

Q7. Draw an ASCII diagram showing the middleware pipeline for a request that passes through: JSON parser, logger, auth check, and route handler.

Q8. List the three things a middleware function can do (its three possible actions on the request-response cycle).


3.6.b — Types of Middleware (Q9--Q17)

Q9. Name the three built-in middleware functions that ship with Express 4.x+. What does each one do?

Q10. What is req.body when you do NOT use express.json() and the client sends a JSON POST request? Why?

Q11. What does the extended: true option do in express.urlencoded({ extended: true })?

Q12. Write the code to serve static files from a public folder with the URL prefix /assets/.

Q13. Name six popular third-party Express middleware packages and describe what each does in one sentence.

Q14. What is the difference between morgan('dev') and morgan('combined')?

Q15. Install commands aside, write the minimal code to enable cors, helmet, and morgan in an Express app.

Q16. You have a custom need: adding a unique request ID to every incoming request. Would you use built-in, third-party, or custom middleware? Why?

Q17. Complete this comparison table:

FeatureBuilt-inThird-partyCustom
Installation???
Maintained by???
Example???

3.6.c — Application-Level Middleware (Q18--Q26)

Q18. What is the difference between app.use(mw) (no path) and app.use('/api', mw)?

Q19. Does app.use('/api', mw) match the URL /application? Why or why not?

Q20. Write code that applies three middleware functions to all routes in a single app.use() call.

Q21. You want logging middleware to run only in development, not production. Write the conditional code.

Q22. Predict which middleware runs for each request:

app.use(express.json());                              // MW1
app.use('/api', (req, res, next) => { next(); });     // MW2
app.use('/admin', (req, res, next) => { next(); });   // MW3
app.get('/', (req, res) => res.send('Home'));
app.get('/api/users', (req, res) => res.send('Users'));
app.get('/admin/panel', (req, res) => res.send('Admin'));

a) GET / -- which middleware runs? b) GET /api/users -- which middleware runs? c) GET /admin/panel -- which middleware runs?

Q23. Why should express.json() be placed BEFORE route handlers that read req.body?

Q24. Write a middleware that adds a X-Request-ID header to every response.

Q25. How do you create a 404 handler using app.use()? Where must it be placed relative to your routes?

Q26. Write a middleware that skips authentication for the paths /health, /login, and /register but enforces it for all other paths.


3.6.d — Router-Level Middleware (Q27--Q33)

Q27. What is express.Router() and how does it differ from the main app?

Q28. Write a complete router file (routes/products.js) with GET / and GET /:id routes, then mount it at /api/products in server.js.

Q29. True or false: Middleware registered with router.use() on one router also runs for routes on other routers. Explain.

Q30. What does { mergeParams: true } do when creating a router? When is it needed?

Q31. You have four resource types: users, products, orders, and reviews. Sketch the project file structure with separate router files and a central route registry.

Q32. Write code for an admin router where every route requires the x-user-role: admin header.

Q33. What are req.baseUrl, req.path, and req.originalUrl when a router is mounted at /api/users and the request is GET /api/users/42?


3.6.e — Custom Middleware Patterns (Q34--Q41)

Q34. Write a middleware factory requireRole(...roles) that returns middleware checking if req.user.role is in the allowed list.

Q35. What is the "async middleware problem" in Express? Why can't you just write app.use(async (req, res, next) => { ... }) without wrapping?

Q36. Write the asyncHandler utility function that wraps an async function and catches errors.

Q37. What is res.locals? How does it differ from adding a custom property directly to req?

Q38. Write a middleware that trims all string values in req.body and req.query.

Q39. Chain the following middleware on a single POST /api/users route: authenticate, requireRole('admin'), requireFields('name', 'email'), and the route handler. Write the Express code.

Q40. Write a configurable cacheControl(maxAge) middleware factory that sets the Cache-Control header.

Q41. Describe a file structure for organizing middleware in a production Express app. Name at least five middleware files and what each contains.


3.6.f — Error Handling and Security (Q42--Q55)

Q42. What is the signature of an Express error-handling middleware? Why must it have exactly that number of parameters?

Q43. What does next(err) do in the middleware pipeline? How is it different from next()?

Q44. Write a centralized error handler that returns JSON with different detail levels for development vs production.

Q45. Predict the output:

app.get('/test', (req, res, next) => {
  next(new Error('Something broke'));
});

app.use((req, res) => {
  res.send('404 Not Found');
});

app.use((err, req, res, next) => {
  res.status(500).send('Error: ' + err.message);
});

What does GET /test return?

Q46. Name five HTTP headers that helmet sets and explain what attack each prevents.

Q47. Why should you never use cors({ origin: '*' }) with credentials: true in production?

Q48. Explain what a CORS preflight request is. What HTTP method does it use? When does the browser send one?

Q49. Write a rate-limiting configuration that allows 5 login attempts per 15 minutes and 100 general API requests per 15 minutes.

Q50. What is CSRF? Describe the attack in 3 steps and name two ways to prevent it.

Q51. Write a custom AppError class that extends Error with a statusCode property and an isOperational flag.

Q52. Where in your Express app should the error-handling middleware be registered? What happens if you put it before your routes?

Q53. You see this error handler but it never catches errors:

app.use((err, req, res) => {
  res.status(500).json({ error: err.message });
});

What is wrong?

Q54. Write middleware that logs all errors to the console and then passes them to the next error handler.

Q55. List seven security best practices for an Express.js application, and name the middleware or technique for each.


Answer Hints

QHint
Q2The request hangs -- client sees a timeout
Q5A, B, C -- D does not run because the route handler sends a response
Q10undefined -- Express does not parse bodies by default
Q11extended: true uses the qs library which supports nested objects
Q19No -- /api is a prefix match, /application starts with /ap not /api/
Q22a) MW1 only; b) MW1 + MW2; c) MW1 + MW3
Q30Allows child router to access req.params from parent router
Q33baseUrl: '/api/users', path: '/42', originalUrl: '/api/users/42'
Q35Unhandled promise rejections bypass Express error handling and can crash the server
Q45Error: Something broke -- next(err) skips the 404 handler and hits the error handler
Q47Browsers reject it; the CORS spec forbids wildcard origin with credentials
Q53Only 3 parameters -- Express treats it as regular middleware, not an error handler. Add next as 4th parameter

<- Back to 3.6 -- Middleware in Express (README)