A user opens the article list and the server returns 401: it did not accept the login credentials on this request. The frontend can exchange a refresh token for a new access token and request the list again. Suppose I also want a log entry: why did the first attempt fail, and what did the page finally receive? If the authentication code passes along only the retry result, logging loses the original 401. Asking the logger to guess which request was a retry gets especially tricky when two pages load at once.
When I wrote Myxios, I wanted functional response interceptors. An interceptor is shared logic that the client invokes during a request. This seemed a good fit for functions: I could check each layer’s input and output independently. Many requests could reuse the same authentication function while the results of each flowed down its own chain. I wanted this separation to improve correctness, especially when requests completed out of order, so one piece of code did not have to guess what another had just changed.1
Is it enough to pass the previous result to the next step?
Start small. Suppose one function selects the response to give the page and a second reads articles from that response. The direct expression is fetch(url).then(selectResponse).then(readArticles). A Promise represents a result that will become available later. If selectResponse is waiting for a retry, readArticles waits too.
The default is convenient: the second function only needs the first function’s return value. The logger, however, needs two values: what the server returned first and what authentication ultimately selected. Myxios keeps the original response for each call and appends each layer’s output in turn. The early README told interceptor authors that “myxios will keep all of the interceptors' response in sequence”.2
| Who is reading? | What can this call see? |
|---|---|
| Authentication starts | [original response] |
| Authentication retry succeeds and logging starts | [original response, retry response] |
| Logging returns its summary | [original response, retry response, log summary] |
There is an interface cost here. Once “the authentication layer returns the final response” is part of the contract, it must return the successful response even when the first attempt succeeds. Then the first two entries point to the same object. The original README implements the success branch that way, allowing every caller in the example to read index 1. As more layers appear, an interface that requires everyone to remember who supplied which position becomes awkward.2
Why use reduce to organize asynchronous functions?
If the caller chooses how many interceptors to register, we cannot hard-code the number of .then() calls. Array reduce starts with an initial value and passes the result of each step to the next. Functional programming calls this a fold. Myxios folds a collection of functions, with a Promise as the accumulating value.3
Here is a teaching implementation based on an early working version. As in the original, the initial value is the fetch Promise. I make the two possible inputs to an interceptor explicit and use await to unfold the callback that merges results.3
function runInterceptors(fetchPromise, interceptors) {
return interceptors.reduce((pendingResults, intercept) => {
return pendingResults.then(async data => {
const previous = Array.isArray(data) ? data : [data];
const added = await intercept(previous);
return [...previous, added];
});
}, fetchPromise);
}
Notice two different orders. reduce can wire up both .then() calls immediately, while the HTTP response is still in flight. Without interceptors, it returns the original fetch Promise. With two interceptors, authentication first gets [original response]. Only after the Promise it returns settles successfully does logging receive the extended array. If authentication throws, these success-only callbacks propagate rejection, and the logger never continues with a half-finished result.4
The easiest expression to test independently is [...previous, added]. Give it an array and the current value and it produces a new array, preserving the old one’s length and positions. Each layer appends one item. If that item is itself a list, it occupies one slot intact. Retrying a network request, reading the response body, and writing logs have observable effects, but testing this merge rule needs only two ordinary values.3
Why don’t two requests using the same functions mix up their results?
The project’s request() passes fetch(url, options) and the registered function array to the dispatcher. When a user requests articles and comments together, the functions are shared, but the dispatcher starts with two different Promises. Request A for articles might start first and pause to refresh a token, then request B for comments might start later and finish first. B’s new array only flows down B’s Promise chain. When A resumes, its previous value still belongs to A.5
This gives a practical design boundary. To time a request, keep its start time in that call. Store it in a shared lastStartTime and B will overwrite A’s time as soon as B starts. Conversely, if both requests receive a 401, they may need to refresh the very same account token. Even with two correct local result chains, they could issue two token refreshes. To guarantee a single refresh, the authentication function must explicitly coordinate shared state. Composition helps identify what is local to one call and what truly needs to be shared.
Angular composes functions too. Why does it pass next to the interceptor?
Start from a function send(req) that already sends a request. To wrap it with authentication and logging, allow each interceptor two inputs: the current request req and a function next describing how to continue. After adding a new token, authentication calls next(modifiedReq) without knowing whether the next layer is another interceptor or the actual transport. Angular’s functional HTTP interceptors use this convention.6
Each layer needs a callable downstream handler. Start with the innermost sender and wrap outward. This adaptation of the Angular 15 source preserves the handler assembly and leaves out framework dependency injection.6
function composeInterceptors(interceptors, send) {
return interceptors.reduceRight((next, intercept) => {
return req => intercept(req, next);
}, send);
}
Given [auth, log], reduceRight first produces a function that calls log with access to send, then passes that function to auth as its next. When handle(req) is finally called, the request enters auth, then log, then send. Right-to-left is the assembly order. Requests still enter layers in registration order.
The other half happens on the return path. Angular’s next(req) returns an Observable, an asynchronous stream of events that can be subscribed to. Authentication retains the original request while handling downstream events or errors. If both interceptors observe responses on their streams, the backend response passes through the inner log before the outer auth. An HTTP 401 comes back through the stream’s error channel as an HttpErrorResponse, where authentication can decide whether to refresh and retry. Native Fetch instead supplies an ordinary Response for a 401, so its status needs checking.78
| Design question | Myxios response chain | Angular functional interceptor chain |
|---|---|---|
| Where does composition start? | The fetch Promise already started for this call | The innermost handler that sends a request |
| What does each layer produce? | A new Promise for the accumulated results of this call | A new request handler that can delegate downstream |
| Who decides when to continue? | The current function returns its result and the Promise chain passes it on. | The current function decides whether to call next(req) and returns the event stream it wants to provide. |
| When can an interceptor act? | Inspect, retry, and consume after a response arrives. | Modify the outgoing request, handle the incoming response or error, or supply a response directly. |
Angular 4.3 already used reduceRight to assemble class-based handlers in 2017. Its interface for registering functions directly and calling next(req) arrived with Angular 15 in 2022. What is worth comparing is the product of composition: one implementation returns something to the caller waiting on this request; the other builds a handler the client can keep and invoke for future requests.96
Back to the article list: what does the caller need?
The early Myxios README shows how to register interceptors once. The example below keeps that interface and simplifies the authentication step to make its return values visible. refreshAndRetryArticles() stands for the application’s own token refresh and article retrieval. It returns a new Response on success and throws on failure.2
async function chooseResponse([original]) {
if (original.status === 401) {
return refreshAndRetryArticles();
}
return original;
}
const [first, selected] = await myxios.requestOneTimeIntercepts(
"/user/articles", { method: "GET" }, [chooseResponse]
);
console.log(first.status, selected.status);
const { articles } = await selected.json();
If the first request succeeds, logging sees 200, 200. If the refresh and retry succeed, it sees 401, 200. The page calls .json() on selected only once. This made functional interceptors worthwhile to me: I can give chooseResponse a successful response and verify that it returns the identical object, or test the retry branch on its own and leave “which page finished first?” out of that function’s tests.
I prioritized response interception because most pages I wrote had some responses that deserved shared handling. The article list and comment list display very different content, but both must handle a 401 after login expires. If each page refreshes the token and resends the request, one authentication change means editing several places. A response interceptor lets both pages share the rule. Once a retry succeeds, each page still decides how to display the selected result.
For pre-request preparation, I put each rule next to the code that makes it easiest to read. If the user selects “drafts only,” code that turns that choice into a query parameter can live beside the article list’s request. For an authentication header common to one API, the early Myxios README passed Authorization in the request options’ headers. Several pages can share that rule through an application helper. Here is an example following the original interface. The application supplies getAccessToken(), which reads the current token on every call.25
function requestApi(path, options = {}) {
const headers = new Headers(options.headers);
headers.set("Authorization", `Bearer ${getAccessToken()}`);
return myxios.request(`/api/${path}`, { ...options, headers });
}
const result = await requestApi(onlyDrafts ? "articles?status=draft" : "articles");
The page now chooses only which articles to request. Header construction and token retrieval live in one place. The Myxios call dispatchRequest(fetch(url, options), …) also explains why this function wraps the request from outside: the first request is already in flight when response interceptors run.5
The difference is clearer when adding another shared rule, such as the current language. In the helper I could call two independent functions that prepare headers in the order written. In Angular I could register authentication and language as separate interceptors, choose which to enable and in what order when configuring the client, and leave pages using that same client.6 Both decouple pages from authentication details. In Myxios I want the library to handle the response interception many pages need. When an ordinary function clearly expresses the outgoing rules, I am happy to leave that composition in the application.
References
Footnotes
-
Cai, B. [S2thend]. (2024, March 12). HttpHandlerTest [Myxios 首次提交
3ef1e4b,1.js]. GitHub. 初版 reduce 和 fetch Promise。文章按该提交时间 2024-03-11 23:43:46 UTC 换算为北京时间归档。初稿将当前项直接交给辅助函数,后续版本才显式调用拦截器。设计初衷于 2026-11-24 回忆整理。 ↩ -
Cai, B. [S2thend]. (2024, March 27). Myxios: Use a one time interceptor [提交
bc40f97,README 示例;引文见拦截器注释第 25 行]. GitHub. 保留各层结果的说明与令牌刷新示例。 ↩ ↩2 ↩3 ↩4 -
Cai, B. [S2thend]. (2024, March 27). Myxios response interceptor dispatch [提交
bc40f97]. GitHub. dispatchRequest 的 reduce 与 then、paramCarryPromise 追加本层的一个结果。 ↩ ↩2 ↩3 -
MDN contributors. (n.d.). Promise.prototype.then() [Return value]. MDN Web Docs. 回调返回另一个 Promise 或抛错时的行为。 ↩
-
Cai, B. [S2thend]. (2024, March 27). Myxios request methods [提交
bc40f97]. GitHub. 复用拦截器的 request 与一次性配置入口。 ↩ ↩2 ↩3 -
Angular team. (2022). interceptor.ts [Angular 15.0.0,chainedInterceptorFn、HttpInterceptorHandler.handle]. GitHub. 给拦截器传入下游函数、从右向左组装并保存函数链。 ↩ ↩2 ↩3 ↩4
-
Angular team. (n.d.). Intercepting requests and responses;Making HTTP requests. Angular. 拦截响应事件、后端错误如何进入错误通道。 ↩
-
MDN contributors. (n.d.). Using the Fetch API [Checking response status]. MDN Web Docs. 检查服务器返回的状态。 ↩
-
Angular team. (2017, July). interceptingHandler [Angular 4.3.0]. GitHub. 用 reduceRight 包装类式拦截器。Angular team. (2022, November 16). Angular v15.0.0 [http 发布说明,introduce functional interceptors]. GitHub. v15 发布说明。 ↩