tezvyn:

Write a request-logging middleware in Express

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

the (req, res, next) signature and calling next().

OUTLINE

read req.method, log with a timestamp, then call next() to continue.

RED FLAG

forgetting next() so the request hangs, or ending the response prematurely.

WHAT THIS TESTS This verifies you understand the fundamental Express middleware signature and the responsibility every middleware has to either end the response or call next().

A GOOD ANSWER COVERS A middleware is just a function with the signature (req, res, next). To log each request, read req.method for the HTTP verb and generate a timestamp such as new Date().toISOString(). Print both to the console, then call next() so Express moves on to the next middleware or route handler. Register it with app.use() before your routes so it runs for every path. The key insight is that next() is what keeps the chain flowing; without it the request never reaches a handler.

COMMON WRONG ANSWERS Forgetting to call next(), which causes the client request to hang until it times out. Calling res.end() or res.send() inside a logger that is not meant to respond, which short-circuits the request. Wrapping next() in a conditional so only some requests proceed. Logging req.url and confusing it with req.method.

LIKELY FOLLOW-UPS How would you also log the response status and duration (capture a start time and listen for res.on('finish'))? Why not use console.log in production (you would reach for a structured logger like pino or morgan)? How does middleware order affect what you can log?

ONE CONCRETE EXAMPLE function requestLogger(req, res, next) { console.log({new Date().toISOString()} {req.method} ${req.originalUrl}); next(); } app.use(requestLogger); A GET to /products prints a line like 2026-06-24T10:00:00.000Z GET /products and then control flows to the matching route. To measure latency you could record const start = Date.now() and log Date.now() - start inside res.on('finish', ...).

Read the original → expressjs.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.