How can Fetch and Express logs trace the same request and its retries?

June 30, 2025

The asset list loaded, but the browser console showed a red 401. In AssetMan, the asset management app I was building, two Fetch response interceptors ran in order. The first, logger(), printed the 401 it saw. The second refreshed the expired token and retried the query with native fetch. If that retry succeeded, the page received a 200. Both status codes mattered. What I wanted to know when reading the logs was whether they belonged to the same click.1

How many requests does one click produce?

Suppose someone clicks “Load assets” just after their access token expires. Here is what the code would report if both the token refresh and the retry succeeded.

Where you lookWhat you seeWhat you can learn
Morgan middleware on the Express serverThree requests in order. The asset query returns 401, the token refresh returns 200, and the second asset query returns 200.Which requests reached the server, and how did it answer each one?
Client logger registered before the authentication interceptorThe 401 from the first query. The refresh uses a separate request function, and the retry calls native Fetch directly. Both bypass this logger.Which response triggered token refresh?
Page code awaiting the asset listA 200. The authentication interceptor replaced the original response with the retry response.Did the operation succeed for the user?

Even for a single request, “duration” depends on who measured it. My client recorded a timestamp just before calling fetch and another when it returned a Response. The page could still be reading the response body. Morgan 1.10.0 measures :response-time from entry into its middleware until the server is ready to write the response headers. A source field lets you tell those two measurements apart when you query them later.23

How do you turn a colored log line into something you can query?

During development, GET /assets 401 18ms is easy to scan. Finding yesterday’s 401s that took longer than a second is easier when status and duration are numeric fields. That is what structured logging buys you. You can filter on status = 401 and durationMs > 1000 without parsing a line of text. In the example below, the caller also assigns an operationId that stays with the operation across retries.

{"source":"server","operationId":"asset-query-7","method":"GET","path":"/assets","status":401,"durationMs":18}

I looked up Morgan on April 23, 2025, and added morgan('dev') to AssetMan’s Express backend the next day. Its color-coded status codes were handy during local development. The version in our lockfile, 1.10.0, could also produce the JSON line above. A custom format function returns a serialized string, and Morgan calls stream.write(line + '\n'). The default stream is standard output, which a log collector can read. The stream option also accepts a custom destination. A service downstream can then store and index the records.43

Why do Express tutorials use Morgan, and what does Pino add?

The official express-generator 4.16.1 scaffolding tool added Morgan as a dependency and registered app.use(logger('dev')) in the generated app.js. Here logger is the imported Morgan function. MDN’s Express library tutorial uses the same setup. Once you’ve written your first route, one browser refresh puts the method, path, status code, and duration in the terminal. That answers the immediate question: did the request reach my route, and what did it return?5

Morgan can include the reason for a 401 in that same line. The authentication code can set res.locals.authReason = 'token_expired' before sending the response. A custom Morgan format function can read the value and include it as a reason field alongside the status. If you prefer a format string, define a token with morgan.token('auth-reason', (req, res) => res.locals.authReason) and use :auth-reason in the string. Morgan’s default completion-time logging gives the authentication handler time to set the value.3

The useful distinction is when an event gets recorded. With Morgan, the reason becomes part of the HTTP access record. With Pino, the authentication code can emit a separate event at the decision point with log.warn({ reason: 'token_expired' }, 'Asset query denied'). The same logging API works during application startup or inside a scheduled job.6

pino-http handles HTTP access logging for Pino. When registered as Express middleware, it automatically logs completed requests and attaches a request-scoped logger to req.log. If the authentication handler calls req.log.warn(...), its warning and the completed request share a request ID. That ID identifies one HTTP exchange. The caller-supplied operationId used here links several exchanges caused by one click.7

How do the browser and server records end up in the same place?

On r/webdev, serg06 already had a Splunk server and asked, “should I create a logging endpoint on my backend and route them through there?”8 An Express route can handle that first hop from the browser.

Here is a local example that extends my original console logger. It assumes a page served from the same origin as an Express app with an existing GET /assets route. Add the following middleware before the asset route. It logs just that endpoint so you can see one client record next to its server counterpart.

const express = require('express');
const morgan = require('morgan');

app.use(morgan((tokens, req, res) => {
  const elapsed = tokens['response-time'](req, res);
  return JSON.stringify({
    source: 'server',
    operationId: req.get('X-Operation-Id'),
    method: req.method,
    path: req.path,
    status: res.headersSent ? res.statusCode : null,
    durationMs: elapsed === undefined ? null : Number(elapsed)
  });
}, { skip: req => req.method !== 'GET' || req.path !== '/assets' }));

app.post('/client-logs', express.json({ limit: '2kb' }), (req, res) => {
  const { operationId, method, path, status, durationMs } = req.body ?? {};
  if (typeof operationId !== 'string' || operationId.length > 64 ||
      method !== 'GET' || path !== '/assets' ||
      !Number.isInteger(status) || !Number.isFinite(durationMs)) {
    return res.sendStatus(400);
  }
  console.log(JSON.stringify({
    source: 'client', operationId, method, path, status, durationMs
  }));
  res.sendStatus(204);
});

On POST /client-logs, express.json({ limit: '2kb' }) parses the browser’s application/json payload into req.body and limits the request body to 2 KiB. The handler then checks the log fields before writing the record.9

Morgan now writes the server record to the terminal. On the client, assign an ID when starting the operation and pass the observation to an output function when the response arrives. I adapted assetQueryLogger below to the original library’s interceptor API. Its default write function logs to the console in either a browser or Node.js. In this browser example, supplying a different write sends the same fields to the collection endpoint.

import { httpClient } from 'express-http-client';

function assetQueryLogger(write = event => console.log(event)) {
  return (data, next) => {
    const { request, response, requestTime, responseTime } = data;
    const path = new URL(request.url).pathname;
    if (request.method === 'GET' && path === '/assets') {
      write({
        operationId: request.headers.get('X-Operation-Id'),
        method: request.method,
        path,
        status: response.status,
        durationMs: responseTime - requestTime
      });
    }
    next();
  };
}

const client = httpClient();
client.addResponseInterceptor(assetQueryLogger(event => {
  // Use native fetch so reporting bypasses the application logger.
  void fetch('/client-logs', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(event)
  }).catch(() => {}); // Best-effort delivery for this local demo.
}));
const api = client.create(location.origin);
await api.send('/assets', {
  headers: { 'X-Operation-Id': crypto.randomUUID() }
});

Run the code once from the same-origin page on localhost. You can match the server and client lines in the terminal by operationId. To follow the retry from the opening example, preserve the header when copying the asset request, pass the same ID to the separate refresh request, and include the refresh route in the server’s access logs. All three HTTP exchanges can then be found together. Each record still reflects its own observer. This small receiver brings the records together on one process’s standard output, where a collector can pick them up for longer-term storage and search.

Why ship a logger with the HTTP client?

I wanted someone using ExpressHttpHandler to be able to register one response interceptor and immediately see what they had just requested. That is much the same convenience the Express generator offered by including Morgan. My May 13, 2025 commit called it “add example request logger middleware”. It doubled as a working example of reading the request and response from data and calling next() to continue. The browser version used %c for color, and Node.js terminals used ANSI colors. By May 21, AssetMan was using the same one-line registration shown in the library README.101

On June 30, I searched for nodejs logger and opened comparisons from Highlight and Better Stack. The versions available today both cover Winston and Bunyan. Highlight also covers loglevel and npmlog, while Better Stack includes Log4js-node, Signale, and Tracer. I can place two individual logger repositories in that afternoon’s history: Pino and Roarr. After searching for frontend logging package, I followed a link from Logging in Browser straight to Roarr’s Motivation section.1112

I also followed Logging for your frontend apps to the Parseable repository. That example showed the whole trip I was interested in: a React app creates events with Pino, sends them over HTTP to Parseable, and makes them available to query at the receiving end.13

I wanted to learn how to preserve the fields in a log event and collect records from both ends of an application. I remember considering a small library that could run in both environments. Shipping a minimal logger as a useful default and a demo fits what I actually built. I no longer remember which particular trade-off in Pino made me want to write my own.11

On a Node.js server, a Pino transport can forward or transform records, for example by uploading them to Elasticsearch in batches. In a browser, browser.transmit.send gives application code the event so it can deliver it to a collector. My HTTP interceptor still has a job in either setup. Its position in the chain tells it which response it saw and whether authentication had already retried the request. In the example above, that knowledge stays in the interceptor. The write function is where I would plug in Pino.1415

For more on how interceptor order determines which Response reaches the page, see my design notes on Express-style middleware for Fetch (in Chinese).


Footnotes

  1. CaiBorui. (2025, May 21). Add support for express http handler [AssetMan commit 54933d5, local Git repository, author’s copy]. See the response interceptor registration, token refresh, and retry branches in frontend/src/utils/ExpressHttpHandler.js. ↩ ↩2

  2. Cai, B. [S2thend]. (2025, May 13). HttpClient.send and Logger [Version 0.3.6 source code]. GitHub. Timing the Fetch call and formatting browser and terminal output. ↩

  3. Express.js contributors. (n.d.). Morgan [Version 1.10.0]. GitHub. Custom tokens, format functions and output streams, and response-header timing and log writes. ↩ ↩2 ↩3

  4. CaiBorui. (2025, April 24). Add login feature; add backend API auth guard [AssetMan commits b94e7c7 and d575fe0, local Git repository, author’s copy]. See the backend npm lockfile for the Morgan version and backend/app.js for its registration. ↩

  5. Express.js contributors. (n.d.). Express application generator [Version 4.16.1]. GitHub. Request logger setup in createApplication. MDN contributors. (n.d.). Express Tutorial Part 2: Creating a skeleton website. MDN Web Docs. Middleware imports and registration in app.js. ↩

  6. Pino contributors. (n.d.). Pino [Version 9.7.0]. GitHub. Usage and child logger context. ↩

  7. Pino contributors. (n.d.). pino-http [Version 10.4.0]. GitHub. Application and access log example and request ID and automatic logging options. ↩

  8. serg06. (2023, March 24). How do you do frontend/client-side logging? [Forum post]. Reddit, r/webdev. First bullet under “Questions”. ↩

  9. Express.js contributors. (n.d.). Express 5.x API reference. Express. express.json(). See the Express Object reference for the type and limit options and the parsed req.body. ↩

  10. Cai, B. [S2thend]. (2025, May 13). Add example request logger middleware [Git commit, quoted from the title]. GitHub. Original middleware and browser output adaptation. ↩

  11. The article date follows the June 30, 2025 reading session. I recorded my recollections and checked the Firefox visit times and Git snapshots on November 24, 2026. The collection example was written for this article. The session included the Pino repository, Collina, M. (n.d.). Multithreaded Logging with Pino. GitNation. Talk, and Kuizinas, G. (n.d.). Logging in Browser. Medium. Article and Roarr’s Motivation section. ↩ ↩2

  12. Highlight. (n.d.). 5 Best Node.js Logging Libraries. Original URL visited. Isaiah, A. (2026, January 17, updated). Logging in Node.js: A Comparison of the Top 8 Libraries. Better Stack. Comparison and contents. The library names follow the available editions. The visit records identify the comparison pages. ↩

  13. Shakti, S. (2022, September 19). Logging for your frontend apps. DEV Community. Sending events from React and querying them in Parseable. On June 30, 2025, I opened the tutorial at 13:56 and followed it to the Parseable repository at 14:09, Beijing time. ↩

  14. Pino contributors. (n.d.). Transports [Version 9.7.0]. GitHub. Worker-thread transports and Elasticsearch delivery. ↩

  15. Pino contributors. (n.d.). Browser API [Version 9.7.0]. GitHub. The transmit option and send callback. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-06-30). How can Fetch and Express logs trace the same request and its retries?. https://caiborui.com/blog/2025-06-30-en-fetch-express-structured-http-logs

@misc{borui2025-9ab7baee,
  author = {borui},
  title = {{How can Fetch and Express logs trace the same request and its retries?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-06-30-en-fetch-express-structured-http-logs}
}