Script Valley
Express.js: APIs and Middleware
Middleware Deep Dive/Assessment

Practice & Assessment

Test your understanding of Middleware Deep Dive

Multiple Choice Questions

5
1

What happens if middleware does not call `next()` and does not send a response?

2

In which order should you register `helmet()`, `cors()`, and your route handlers?

3

What is the correct way to attach the authenticated user to the request in Express?

4

What does the `res.on('finish')` event in a logger middleware fire on?

5

Which middleware function signature indicates an Express error-handling middleware?

Coding Challenges

1
1

Build a Middleware Pipeline

Create an Express app with three custom middleware functions applied globally: (1) a request logger that prints method, URL, and timestamp to console, (2) a request-id middleware that attaches a unique ID (use Date.now() + Math.random()) to req.requestId, and (3) a response-time middleware that logs how long each request took. Apply them with app.use in the correct order. Add a GET /ping route that returns { pong: true, requestId: req.requestId }. Inputs: any HTTP request. Outputs: JSON body with requestId plus console logs for each request. Time estimate: 20 minutes.

Easy

Mini Project

1

API Gateway Middleware Stack

Build an Express app that simulates an API gateway. Implement: (1) a logger middleware logging method, URL, status, and duration; (2) an API key authentication middleware checking the x-api-key header against a hardcoded list of valid keys, returning 401 for invalid/missing keys; (3) a rate-limit middleware using an in-memory object to track requests per API key, returning 429 after 10 requests per minute; (4) a requireFields middleware factory used on POST routes. Mount all routes under /api/v1. Include at minimum: GET /api/v1/status, POST /api/v1/data (requires fields: type, payload). The auth and rate-limit middleware should be applied globally after the logger.

Medium
Practice & Assessment โ€” Middleware Deep Dive โ€” Express.js: APIs and Middleware โ€” Script Valley โ€” Script Valley