Skip to content

Simple Logger Middleware Pattern

Wrap a Node.js request handler so each response logs method, URL, status, and elapsed milliseconds when the response finishes.

Language: Node.js

Added on: 21st August 2026

function withLogging(handler) {
  return (req, res) => {
    const start = Date.now();
    res.on("finish", () => {
      console.log(req.method, req.url, res.statusCode, `${Date.now() - start}ms`);
    });
    handler(req, res);
  };
}

Caveats

Framework-free: pass this wrapper to http.createServer. Logs on the finish event, so early socket drops may not appear. statusCode is 200 until the handler sets another.