ReviewOS

stacks/stx

feat(data): no request/response interceptor — useFetch/useQuery/useMutation cannot carry auth or observe a 401

#1855
Closed glennmichael123 opened this 22 days ago · 4 comments
22 days ago

Summary

stx's client data layer has no hook between the composable and fetch. __stxFetch (packages/stx/src/signals.ts:161-172) calls fetch(url, opts) directly, and useFetch/useQuery/useMutation accept headers only as a plain object captured when the composable is created. There is no way to attach a per-call bearer token, and no way to observe or act on a response before the composable throws. All three implementations throw new Error('HTTP ' + status) before reading the body, so the server's own error message is unreachable and a 401 cannot be turned into a token refresh + retry.

The practical result is that an app with authenticated endpoints cannot use the framework's data layer at all.

Impact (real app)

analyticshq is an analytics SaaS; every data endpoint is bearer-authenticated. We wrote our own client:

  • resources/stores/session.ts:215-240 — authFetch(input, init): attaches the header, detects 401, renews, retries once.
  • resources/stores/session.ts:124-127 — bearer() builds the header object.
  • 10 call sites go through it: resources/views/dashboard.stx:859, 883, 908, 926, 1031, 1049; resources/views/account.stx:54; resources/views/sites/new.stx:45; resources/views/pricing.stx:35.

grep -rn 'useFetch(\|useQuery(\|useMutation(' resources/ app/ returns zero hits across the whole app.

The store documents why it had to exist (resources/stores/session.ts:206-213):

Every authenticated call on this page goes through session.authFetch, which attaches the bearer header, renews an expired access token and retries once (#32). The local authHeaders() helper that used to live here only attached the header, so an hour into a session this whole page 401'd: goals could not be added or deleted, share links […]

Because authFetch can only return a raw Response, every consumer re-implements status handling and JSON parsing:

// resources/views/dashboard.stx:1031-1034
session.authFetch('/api/me')
  .then(r => r.ok ? r.json() : null)
  .then(d => { if (d && d.pro) isPro.set(true) })
  .catch(() => {})

That shape is repeated at all 10 call sites. None of them gets { data, loading, error }.

Evidence in stx

packages/stx/src/signals.ts:161-172 — the single choke point, with no hook:

async function __stxFetch(source, url, opts) {
  var t0 = __stxDevtoolsNow();
  var method = (opts && opts.method) || 'GET';
  try {
    var r = await fetch(url, opts);          // ← no onRequest / onResponse
    __stxDevtoolsRecordQuery({ ... });
    return r;
  } catch (e) { ... }
}

packages/stx/src/signals.ts:955-961 (useFetch), :1243 (useQuery), :1319-1323 (useMutation) each build headers from a static options object:

var fetchOpts = { method: 'GET', headers: { 'Content-Type': 'application/json', ...(options.headers || {}) } };

packages/stx/src/signals.ts:1325 (useMutation) — body unreachable on failure:

if (!response.ok) throw new Error('HTTP ' + response.status + ': ' + response.statusText);
var result = await response.json();

Same at :971-973 (useFetch) and :1245 (useQuery).

packages/stx/src/runtime-globals.ts:43-58 — STX_RUNTIME_GLOBALS exposes no fetch-configuration or interceptor name, so there is nothing an app could reach for even out-of-band.

Prior art

  • Angular: HTTP_INTERCEPTORS multi-provider + HttpClient; every request passes through the chain.
  • axios: instance.interceptors.request.use(fn) / interceptors.response.use(ok, err).
  • Nuxt/ofetch: $fetch.create({ onRequest, onRequestError, onResponse, onResponseError }), and useFetch runs through it.
  • TanStack Query: new QueryClient({ defaultOptions: { queries: { queryFn } } }) — one shared fetcher for every query.

Ask

  1. Add a configurable fetch instance that __stxFetch routes through, e.g. createFetch({ baseURL, onRequest, onResponse, onResponseError }), exposed as a runtime global and settable once per app (setDefaultFetch(instance)).
  2. Accept headers as Record<string,string> | (() => Record<string,string>) in useFetch/useQuery/useMutation, resolved per request rather than at creation.
  3. Stop throwing before the body is read: attach the parsed body to the error (err.data, err.status, err.response) so {message} / {error} payloads are reachable by consumers.
  4. Give onResponseError the ability to return a replacement response, so a 401 → refresh → retry can be expressed once in framework code instead of per app.

Related: #1843 (adoption report — this is the concrete reason the data layer went unused in a second app), #1726 (the two useFetch impls).

22 days ago

Implemented in f4a545b — but scoped down substantially from what the issue proposes, so worth a look before merging.

The issue asks for createFetch({ baseURL, onRequest, onResponse, onResponseError }). That is an instance factory plus a URL-building layer plus four hooks. All three primitives already funnel through __stxFetch, the only fetch call in the runtime, so the smallest thing that solves the stated problem is one function and two hooks on that choke point:

configureFetch({
  onRequest: ctx => { ctx.options.headers.Authorization = 'Bearer ' + token() },
  onResponse: ctx => { if (ctx.response.status === 401) navigate('/login') },
})

No baseURL option: ctx.url is reassignable, so prefixing one is already expressible. No onResponseError: #1848 landed, so the error carries status/data and a caller can branch on it. The rest can be added against real demand rather than guessed at now.

Hooks mutate the context and the return is ignored — the ofetch shape most people already know. Throwing fails the request, which is what a token-refresh flow wants. Calling configureFetch again replaces rather than stacks, so a module re-evaluated by hot reload or re-run after an SPA swap can't end up sending two Authorization headers.

Note that ask 3 of the issue is already shipped — reading the body before throwing landed in 765b168 (#1848), so that part of the description is stale.

Adjacent silent hole fixed while here: headers was spread as ...(options.headers || {}), and object spread over a function copies no own enumerable properties. So headers: () => ({ Authorization: ... }) — the obvious way to evaluate a token per request — contributed exactly nothing, with no error anywhere.

Registered in STX_RUNTIME_GLOBALS and declared in stx.d.ts, since an interceptor unreachable from a <script client> is the same as no interceptor; ambient-declarations.test.ts enforces that pairing and caught the missing declaration. 15 tests, all 15 failing without the change, each hook asserted against all three primitives rather than one.

22 days ago

Claiming this one — working on it now. It's my home turf: I landed the AbortController work in these exact three primitives (#1871) and the poll-visibility gating (#1870), all in signals.ts. Plan follows the four asks: (1) a createFetch({ baseURL, onRequest, onResponse, onResponseError }) instance + setDefaultFetch, routed through __stxFetch, exposed as a runtime global; (2) headers accepted as Record | (() => Record) and resolved per request; (3) stop throwing before the body is read — attach err.data/err.status/err.response; (4) onResponseError may return a replacement Response so 401→refresh→retry is expressible once in framework code. Isolated to signals.ts + one runtime-globals entry + a .d.ts line, so no collision with the router/bundler work.

22 days ago

Landed the last of the four asks — closing.

The data layer now has a full interceptor surface, all funnelled through __stxFetch so one registration covers useFetch/useQuery/useMutation:

  • Ask 1 — configurable instance / runtime global: configureFetch({ onRequest, onResponse, onResponseError }), exposed on window.stx and in STX_RUNTIME_GLOBALS (so a bare call works from <script client>). Re-registration replaces rather than stacks, so a hot-reloaded or SPA-re-run module can't install the same hook twice. (f4a545bf0b)
  • Ask 2 — per-request headers: headers accepted as Record | (() => Record) and resolved per call via __stxHeaders; a function used to contribute nothing because object-spread over a function copies no own props. (f4a545bf0b)
  • Ask 3 — body reachable on failure: __stxHttpError reads the body first and attaches err.status/err.statusText/err.data/err.response (also #1848), so a validation map or rate-limit reason survives to the consumer. (f4a545bf0b)
  • Ask 4 — recovery hook (this commit, 0997c4a063): onResponseError fires for a non-ok response and for a thrown fetch (network error, response: null). Returning a Response replaces the failed one — the 401 → refresh → retry shape: the hook refreshes the token, re-issues with a plain fetch() (so it doesn't re-enter the hook and loop), and returns that Response. Returning nothing leaves the original error standing.

Tests in packages/stx/test/signals/fetch-interceptors.test.ts (21 pass) cover the non-ok path, the network-throw path, the no-op path, header resolution, and reach across all three primitives.

22 days ago

Actioning the close stated above — the issue was left open.

Verified at 47a7482c77: packages/stx/test/signals/fetch-interceptors.test.ts is 21 pass / 0 fail, and configureFetch is present in STX_RUNTIME_GLOBALS with its stx.d.ts declaration, so the bare call resolves from a client script. All four asks are covered across f4a545bf0b and 0997c4a063.

Sign in to comment on this issue.