Skip to content

Instantly share code, notes, and snippets.

@ReaganS94
Last active October 20, 2025 10:19
Show Gist options
  • Select an option

  • Save ReaganS94/1bc080e3cc6b9e33bbff60250e8d9355 to your computer and use it in GitHub Desktop.

Select an option

Save ReaganS94/1bc080e3cc6b9e33bbff60250e8d9355 to your computer and use it in GitHub Desktop.

App-level middleware exercises

Context: you already have the MVC starter shown above. Do not change controllers, schemas, or routes for these tasks.

Ground rules

  1. Do not remove existing functionality. You can replace the placeholder app-level middleware if the task tells you to.

  2. Put new app-level middleware above app.use("/api/students", student) and above the 404 handler.

  3. Do not add new files. Everything stays in server.js for this pair of exercises.

  4. Test with Postman.


Exercise 1: request summary logger and response header

Goal: create a simple app-level middleware that helps you see what is hitting your server.

What to build

  • Replace the current placeholder app-level middleware that logs "I am an application level middleware" with a new middleware named requestSummary.

  • It must print to the console: HTTP method, original URL, and an ISO timestamp of when the request arrived. One line per request.

  • It must attach a response header named X-Request-Received with the same ISO timestamp.

  • It must call next() so that routes continue to work.

Where to put it

  • Place requestSummary after app.use(cors()) and before app.use("/api/students", student).

Starter scaffold (paste in server.js and fill the TODOs)

// App-level: request summary logger
function requestSummary(req, res, next) {
  // TODO 1: create an ISO timestamp string
  // TODO 2: console.log one line with method, originalUrl, and the timestamp
  // TODO 3: set a response header named "X-Request-Received" to the timestamp
  // TODO 4: call next()
}

// register it here
// app.use(requestSummary);

How to set a response header in Express (quick primer)

  • A response header is metadata sent before the body. You must set it before res.send(...) or res.json(...) or the headers will already be locked.

  • Do it inside your middleware, then call next() so the request continues to the route handlers.

  • You can use either of these (they behave the same for our use case):

    • res.set(name, value) or res.set({ name: value })

    • res.setHeader(name, value) (Node.js style)

  • Header names are case-insensitive. Use a conventional hyphenated form like X-Request-Received.

  • Common mistakes to avoid: forgetting next(), setting the header after you already sent the response, or trying to set res.headers (that property does not exist).

Mini example

function requestSummary(req, res, next) {
  const ts = new Date().toISOString();
  res.set('X-Request-Received', ts); // set the header
  console.log(req.method, req.originalUrl, ts);
  next();
}

Quick checks (Postman)

GET base URL

  1. Open Postman and create a request. Set Method to GET and URL to http://localhost:5000/.

  2. Send the request.

  3. In the response, open the Headers tab and confirm X-Request-Received is present with an ISO timestamp.

  4. Check your server console. You should see a single line like GET / <time>.

POST create student

  1. Create a new request. Set Method to POST and URL to http://localhost:5000/api/students.

  2. In Headers, add Content-Type: application/json.

  3. In Body, select raw and JSON, then paste:

{
  "first_name": "Ada",
  "last_name": "Lovelace",
  "email": "ada@love.com",
  "age": 30
}
  1. Send the request.

  2. Expect Status 201 Created and the X-Request-Received header in the response. The console should log one line like POST /api/students <time>.


Exercise 2: maintenance mode gate and response time logger

Goal: level up the previous exercise. Add a guard that can short-circuit requests when maintenance is on, and enhance logging with status code and duration.

What to build

  1. Performance logger upgrade

    • Start a timer at the moment the request arrives.

    • Use res.on("finish", ...) to log a single line after the response is sent.

    • That log line must include: HTTP method, original URL, status code, and duration in milliseconds.

    • This should replace or upgrade the logger from Exercise 1. You still keep the X-Request-Received header from Exercise 1.

  2. Maintenance gate

    • Create a second app-level middleware named maintenanceGate that checks an environment variable, for example process.env.MAINTENANCE_MODE.

    • If the value is the string on, immediately respond with status 503 and a small JSON body like { msg: "Server under maintenance" }. Do not call next() in this case.

    • If maintenance is not on, call next().

Order matters

  • Register the performance logger first, then the maintenance gate, then your routes. This ensures you still see a completed log line even when the gate blocks requests.

Starter scaffold (paste in server.js and fill the TODOs)

// App-level: performance logger with status and duration
function performanceLogger(req, res, next) {
  // TODO 1: capture start time now
  // TODO 2: ensure the ISO timestamp header from Exercise 1 is still set
  // TODO 3: after response finishes, log method, url, res.statusCode, and elapsed ms
  // Hint: use res.on("finish", () => { /* log here */ })
  // TODO 4: next()
}

// App-level: maintenance gate
function maintenanceGate(req, res, next) {
  // TODO 1: check process.env.MAINTENANCE_MODE
  // TODO 2: if it equals "on", send status 503 with a small JSON message and return
  // TODO 3: otherwise call next()
}

// register them in this order
// app.use(performanceLogger);
// app.use(maintenanceGate);

How to test the gate (Postman)

Turn maintenance on

  1. Set the environment variable and restart the server (MAINTENANCE_MODE=on)

Request in Postman

  1. Create a GET request to http://localhost:5000/api/students.

  2. Send the request. You should see Status 503 Service Unavailable with a body like:

{ "msg": "Server under maintenance" }
  1. Check the server console. Your performance logger should still print a completed line with method, url, status, and duration.

Turn maintenance off and retest

  1. Set the variable to off and restart the server ( MAINTENANCE_MODE=off)

  2. Send the same GET request in Postman.

  3. You should get the normal response (for example, 200 OK), and the console log should include method, url, status, and duration.


Done criteria

  • Exercise 1 prints a clear one line request summary and sets X-Request-Received for every response.

  • Exercise 2 logs method, url, status, and duration using res.on("finish").

  • Exercise 2 blocks requests with status 503 when MAINTENANCE_MODE=on.

  • Middlewares are registered above the student routes and above the 404 handler.

  • No new files were added and controllers or schemas were not modified.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment