Managed HTTP reference¶
Describe an HTTP request as data in an event's :fx, and the runtime issues it, applies your timeout and retry policy, decodes and validates the body, classifies any failure into a closed set of kinds, and dispatches the reply to an event you name. Aborting and superseding a request by id are built in.
Use :rf.http/managed directly for a request whose reply one event handles, such as a login or a one-off load you keep in your own app-db. When the same server data is read from more than one place, or needs caching, deduplication, staleness or a refetch after a write, register a resource instead. Resources and mutations issue their requests through this same fx: their request fns return the args map described below, and the runtime supplies the reply addressing.
Managed HTTP ships in the optional artefact day8/re-frame2-http. Require re-frame.http.managed once at boot: loading it registers the :rf.http/managed fx. Without it, each use of the fx reports :rf.error/no-such-fx and no request is made. A facade call such as rf/reg-http-interceptor made without the artefact raises :rf.error/http-artefact-missing.
(:require [re-frame.core :as rf]
;; Registers the `:rf.http/managed` fx at ns-load. Require it once,
;; at boot — nothing on the `rf/` facade does it for you.
[re-frame.http.managed])
(rf/reg-event :cart/load
(fn [_ _]
{:fx [[:rf.http/managed
{:request {:method :get :url "/api/cart"}
:decode :json
:on-success [:cart/loaded]
:on-failure [:cart/load-failed]}]]}))
(rf/reg-event :cart/loaded
(fn [{:keys [db]} [_ {:keys [value]}]]
{:db (assoc-in db [:cart :items] value)}))
(rf/reg-event :cart/load-failed
(fn [{:keys [db]} [_ {:keys [error]}]]
{:db (assoc-in db [:cart :load-error] error)}))
(rf/reg-sub :cart/items
(fn [db _] (get-in db [:cart :items])))
Retries, timeouts, abort, decode and accept checks are further optional keys in the same args map.
There is no re-frame.http namespace and no per-verb helper. The fx are addressed by keyword, reg-http-interceptor is called on the facade as rf/reg-http-interceptor, and the stub transports are functions in re-frame.http.stub-transport. An app that issues many requests usually writes its own function that builds the args map, adding a base URL, default headers, a default :decode and body encoding; see Your own request builder.
Managed HTTP teaches the model.
Effects¶
[:rf.http/managed args-map]¶
- Kind: effect (reserved fx-id)
- Payload: the args map below. The request is a map covers the
:requestenvelope. - Description: Issues one HTTP request and dispatches its reply to the target the args map names. In the browser it uses Fetch; on the JVM,
java.net.http.HttpClient.- Destroying the issuing frame, or restoring an epoch in it, aborts the frame's in-flight requests; no reply is delivered.
- A request issued from inside a spawned machine actor is aborted when that actor is destroyed. Its reply target receives
:status :cancelledwith:rf.reply/cancel-reason :actor-destroyed, unless the target is the actor itself, which receives nothing. - An abort that lands between retry attempts cancels the pending retry.
- On the JVM, a relative
:urlfails as:rf.http/transport, cookies are neither sent nor stored, the response:status-textis"", and a connection not made within 10 seconds fails as:rf.http/timeout.:abort-signaland the CLJS-only:requestkeys are ignored, with a:rf.http/cljs-only-key-ignored-on-jvmtrace.
-
Options:
:requestis required, and every request names where its reply goes with:reply-toor:on-success/:on-failure.Key Value Default Meaning :requestmap required The request envelope, in the second table below. :decode:auto,:json,:text,:blob,:array-buffer,:form-data, a Malli schema or a fn:autoHow to read a 2xx body; the forms are listed below this table. JSON object keys decode to keywords. :accept(fn [decoded] …)none: every decoded 2xx body is a success A domain check after decoding. Returning {:ok value}makesvaluethe success:value; returning{:failure user-map}fails the request as:rf.http/accept-failure.:retry{:on #{kinds-and-statuses} :max-attempts N :backoff {:base-ms :factor :max-ms :jitter}}none: nothing is retried The retry policy; its rules are below this table. :timeout-msmilliseconds, nilor030000The per-attempt timeout. An explicit nilor0turns it off.:rf.http/max-decoded-keysinteger 10000The most unique JSON object keys the decoder will intern for this request. Exceeding it fails the request as :rf.http/decode-failurewith:reason :too-many-keys.:reply-toevent vector or nilnone Receives both the success and the failure reply; see Reply addressing. :on-success/:on-failureevent vector or nilnone Separate success and failure targets, used instead of :reply-to.:request-idany =-comparable valuenone Names the request, for :rf.http/managed-abortor supersession; see below this table.:abort-signalan external abort signal none Aborts the request when it fires. CLJS only. :sensitive?boolean falseRedacts this request in traces; see Privacy and classification. :decodetakes four forms::auto, the default when absent: ajsonor+jsonContent-Typedecodes as JSON,text/*as a string, and anything else, including noContent-Type, as a binary body (aBlobin the browser, abyte[]on the JVM).:json,:text,:blob,:array-bufferor:form-dataforces one.- A Malli schema parses JSON and validates it. It decodes only a response whose
Content-Typeis JSON or absent; any other type fails as:rf.http/decode-failure. It needs Malli at run time, andday8/re-frame2-httpdoes not bring it: addday8/re-frame2-schemasand requirere-frame.schemasat boot. Without Malli, a request with a schema:decodeis refused at dispatch with:rf.error/schemas-artefact-missing, before anything is sent. See Response-body classification for the schema's:sensitive?and:large?props. - A fn
(fn [body-text headers] → value)does it all. It receives the raw body text (""for an empty body), and a throw fails as:rf.http/decode-failure.
:retry::onmust be a set whose members are retryable kinds,#{:rf.http/transport :rf.http/timeout :rf.http/http-4xx :rf.http/http-5xx}, or HTTP status integers from 400 to 599, which match a failure carrying that:http-status. So#{:rf.http/http-5xx 429}retries every 5xx and a 429, where:rf.http/http-4xxwould also retry 400, 401, 403, 404 and 422.#{}ornilretries nothing.:max-attemptsis required in a:retrymap and counts the first attempt, so3means up to two retries; a:retrymap without it is refused rather than defaulted, because every extra attempt re-sends the request.:backoffdefaults to{:base-ms 250 :factor 2 :max-ms 5000}, and:jitter trueadds ±25%. Only the final failure reaches your reply target.:request-id: issuing a new request with the same id while one is in flight supersedes it, and the old reply is never delivered. Ids are per frame, so two frames running the same code do not cancel each other.
The
:requestenvelope:Key Value Default Meaning :urla non-blank string required The request URL. On the JVM it must be absolute. :method:get,:head,:post,:put,:patch,:deleteor:options:getThe HTTP method. :headersheader name to a string, or to a vector of strings for a repeated header none Names are case-insensitive. A header the platform rejects is left out, with a :rf.warning/http-header-invalidtrace.:paramsa query-param map none Encoded onto the URL before any #fragment; its rules are below this table.:bodya Clojure collection, a string, a FormData,BloborArrayBuffer, or a no-argument fn returning onenone The request body; its rules are below this table. :request-content-type:json,:form,:textor a MIME stringnone: chosen from :bodySerialises :bodyand setsContent-Type, unless:headersalready sets one; the rule without it is below this table.:credentials:omit,:same-originor:include:same-originPassed to Fetch. CLJS only. :mode:cors,:same-origin,:no-cors:corsBrowser Fetch mode. :no-corscannot provide a readable cross-origin response; it is not a way to bypass CORS. CLJS only.:cache:default,:no-store,:reload,:no-cache,:force-cache,:only-if-cached:defaultBrowser HTTP-cache policy; see below. CLJS only. :referrersame-origin URL string, "", or"about:client""about:client"URL to use as referrer, no referrer, or the client's referrer. CLJS only. :integritya subresource-integrity string none Expected response hash, such as "sha256-…". CLJS only.:redirect:follow,:erroror:manual:followWith :erroror:manual, a redirect response fails the request instead of being followed.:sensitive?boolean falseThe same as the top-level :sensitive?.:params: a sequential value repeats the key ({:tag ["a" "b"]}→tag=a&tag=b); an empty sequence adds nothing.nilemits an empty value (tag=). Keyword keys use their unqualified name, while keyword values keep their namespace without the colon ({:sort :order/asc}→sort=order%2Fasc). Other scalar values are stringified. Existing query pairs are retained; params are appended before any fragment.:body: the fn is called before each attempt, so a retry gets a fresh body. A fn that throws, or a body the encoder rejects, fails the request as:rf.http/transportwith:stage :request-prep.:request-content-type::jsonJSON-encodes the body and setsapplication/json;:formURL-encodes a map and setsapplication/x-www-form-urlencoded;:textstringifies the body and setstext/plain. An explicit MIME string stringifies the body and sets that MIME type:"application/json"does not JSON-encode a Clojure map, so use:jsonfor that. Without the option, a Clojure map, sequence or set is JSON-encoded; other bodies pass through unchanged without an inferred header. Anilbody sends no body and infers no content type. An explicitContent-Typeheader wins over the inferred header, but does not change the encoding selected here. JSON writes a keyword with its namespace and no colon (:user/id→"user/id") and a UUID as its string.:cache::defaultuses normal HTTP freshness rules;:no-storebypasses the cache;:reloadfetches and updates it;:no-cacherevalidates a cached response;:force-cacheaccepts a cached response regardless of freshness;:only-if-cachedrequires one and requires:mode :same-origin. These are Fetch options, separate from a re-frame resource cache. The browser validates their combinations. Although Fetch defines a navigation mode, application requests cannot use:mode :navigate.- Errors, all raised at dispatch, before the request is sent. The effect throws: the request is not sent, no reply is dispatched, the event's other effects still run, and error listeners receive
:rf.error/fx-handler-exception, whose:exceptioncarries the id below: :rf.error/http-bad-request— the final:url, after the:beforeinterceptor chain, is missing,nil, non-string or blank.:rf.error/http-bad-retry-on—:retry :onis not a set of retryable kinds and statuses from 400 to 599, or a:retrymap has no:max-attempts.:rf.error/http-bad-reply-target— a reply-target value that is neither an event vector nornil;:reply-tobeside:on-success/:on-failure(:reason :mixed-addressing); or one of:on-success/:on-failurewithout the other (:reason :unpaired-split).:rf.error/http-no-reply-target— none of:reply-to,:on-successor:on-failureis present.:rf.error/schemas-artefact-missing— the:decodeis a schema but Malli is not loaded, so the response could not be validated; or the schema carries a:sensitive?or:large?prop butre-frame.schemasis not loaded, so the response could not be classified. Addday8/re-frame2-schemasand requirere-frame.schemasat boot.:rf.error/bad-classification— the:carriersblock on the:rf.http/managedregistration is malformed; see Privacy and classification.reg-fxaccepts the block, and every request refuses it until it is fixed.:bad-keynames the offending slot. In a development build this id also escapes the event:dispatch-syncthrows it, and the event's later effects do not run.- Example:
(rf/reg-event :cart/load (fn [_ _] {:fx [[:rf.http/managed {:request {:method :get :url "/api/cart"} :request-id :cart/load :timeout-ms 5000 ;; 429 retries a rate limit without retrying every 4xx. :retry {:on #{:rf.http/transport :rf.http/http-5xx 429} :max-attempts 3} :on-success [:cart/loaded] :on-failure [:cart/load-failed]}]]}))
[:rf.http/managed-abort request-id]¶
- Kind: effect (reserved fx-id)
- Payload: the
:request-idof an in-flight request. - Description: Aborts the in-flight request with that
:request-id, issued from the same frame; an id with nothing in flight is a no-op. Its reply target (:reply-toor:on-failure) receives the cancelled reply{:status :cancelled :rf.reply/cancel-reason :user :error {:kind :rf.http/aborted ...}}, as described under Reply shape. See Cancellation: supersession and abort, which compares abort with supersession. - Example:
{:spawn {:machine-id :rf.http/managed :data args-map}}¶
- Kind: machine (registered when
re-frame.machinesis also loaded) - Payload:
:datais an:rf.http/managedargs map without reply addressing. - Description: Runs one request as a child machine, so the request lives exactly as long as the parent state that spawns it.
- The child finishes in a final
:succeededor:failedstate holding the reply's:value, or its:errorfailure map, under:rf/result. - The child completes like any child machine: under
:spawn, the parent's:on-donereceives the value as the completion's:resultand its:on-errorthe failure; under:spawn-all, the result folds into the join. - Leaving the parent state aborts the request, and the parent receives no completion.
- The child sets its own
:on-success/:on-failure, so:datamust not carry:reply-to,:on-successor:on-failure. Any of them makes the child throw:rf.error/http-bad-reply-target(:reason :machine-owns-reply,:keysnaming them) when it starts, before a request is sent. The runtime reports the throw as:rf.error/machine-action-exception, with the error in its:exception-data, and routes it to the parent's:spawn :on-error. - See From a state machine, which also shows
:spawn-allfan-out.
- The child finishes in a final
- Example:
Replies¶
Reply shape¶
Every reply is one map keyed on :status, which is :ok, :error or :cancelled:
;; Success — :meta carries the response's :http-status, :status-text and :headers
;; (header names lower-cased)
{:status :ok :value decoded-body :meta {:http-status 200 :status-text "OK" :headers {…}} …}
;; Failure — per-kind tags (:http-status / :status-text / :message / ...) sit
;; flat on the failure map beside :kind
{:status :error
:error {:kind :rf.http/<kind> ...}}
;; Abort / cancel
{:status :cancelled :rf.reply/cancel-reason :user
:error {:kind :rf.http/aborted …}}
A timeout is a failure: :status :error with :kind :rf.http/timeout. The reply also carries :attempt and, when the request had a :request-id, :correlation {:request-id …}.
A reply from a real request (not a test stub) adds:
:rf.reply/work-status—:completed(:ok),:failed(:error),:timed-out(a:rf.http/timeoutfailure) or:cancelled.:rf.reply/work-id—[:rf.work/http issuance attempt], the join to the trace stream, and:rf.reply/work-kind :http.:rf.frame/id— the issuing frame.:completed-at— the completion time in epoch milliseconds. The reply event's:rf/time-mscoeffect carries the same value.- On
:cancelled,:rf.reply/cancel-reasonis:user(:rf.http/managed-abortor:abort-signal) or:actor-destroyed. Supersession, frame destroy and epoch restore deliver no reply.
Reply addressing¶
Every request must name where its reply goes. The runtime appends the reply map as the last argument of the event vector you name:
:reply-tosends both the success and the failure reply to one event; resources and mutations use the same key. A:cart/loadhandler addressed with:reply-to [:cart/load]receives[:cart/load {:status :ok :value decoded-body …}](or the:error/:cancelledshape) and branches on(:status reply). Put request context in the vector::reply-to [:cart/load ctx]delivers[:cart/load ctx <reply>].:on-success/:on-failureroute the same reply map to two events, and are always supplied together. A:cart/loadedhandler receives[:cart/loaded {:status :ok :value decoded-body …}]and destructures it directly:[_ {:keys [value]}]for success,[_ {:keys [error]}]for failure. Neither may appear beside:reply-to; the check is on key presence, so anilvalue counts.:reply-to nilmeans fire-and-forget: no reply is delivered.:on-success nilor:on-failure nildrops one side of the split form.- Supplying only
:on-success, or only:on-failure, raises:rf.error/http-bad-reply-targetwith:reason :unpaired-split, and nothing is sent: the branch left out would drop its replies with no handler. Writenilfor a side you mean to drop. - Omitting all three keys raises
:rf.error/http-no-reply-target: the framework never picks a reply target for you, because an implicit target can swallow failures.
The cell below answers two requests from a stub transport and shows the whole event each reply arrives as: the :reply-to vector, context map included, with the reply map appended.
(require '[re-frame.core :as rf]
'[re-frame.http.managed]
'[re-frame.http.stub-transport :as stub-transport])
;; A fake backend for this frame: the cart loads, and a missing cart fails
;; with a 404. A real app installs no transport.
(stub-transport/install-transport! :app/cart
(stub-transport/route-transport
{[:get "/api/cart"] {:body [{:id 1 :name "widget"}]}
[:get "/api/cart/missing"] {:status 404 :status-text "Not Found" :body "no such cart"}}))
(rf/reg-event :cart/load
(fn [_ [_ url]]
{:fx [[:rf.http/managed {:request {:method :get :url url}
:reply-to [:cart/reply {:url url}]}]]}))
;; Keep the whole event the reply arrived as.
(rf/reg-event :cart/reply
(fn [{:keys [db]} event]
{:db (assoc db :cart/last-reply event)}))
(rf/reg-sub :cart/last-reply (fn [db _] (:cart/last-reply db)))
(rf/reg-view reply-view []
[:div
[:button {:on-click #(dispatch [:cart/load "/api/cart"])} "Load the cart"]
" "
[:button {:on-click #(dispatch [:cart/load "/api/cart/missing"])} "Load a missing cart"]
[:pre {:style {:white-space "pre-wrap"}}
(pr-str @(subscribe [:cart/last-reply]))]])
[rf/frame-root {:id :app/cart}
[reply-view]]
Handling the reply shows both styles in full.
Failure kinds (closed set)¶
A failure's :kind is one of seven values, all reserved under :rf.http/*. The set is closed, so a handler's case on :kind can be exhaustive.
:kind |
Meaning | Tags |
|---|---|---|
:rf.http/transport |
Network, DNS or connection error before any HTTP response, or a :body that could not be prepared. In the browser a Fetch rejection against a cross-origin URL carries :cross-origin? true: the browser reports a CORS refusal and a dropped connection the same way, so it may be either. |
:message, :cause; :stage :request-prep for a body failure; :cross-origin? true (CLJS only) |
:rf.http/timeout |
The per-attempt timeout fired. | :elapsed-ms, :limit-ms; on the JVM also :message |
:rf.http/http-4xx |
A 4xx response, or any other non-2xx status below 500 (a 1xx, or a 3xx that was not followed). | :http-status, :status-text, :body (parsed when the Content-Type is JSON, else raw text), :body-text (raw text), :headers |
:rf.http/http-5xx |
A 5xx response. | :http-status, :status-text, :body (parsed when the Content-Type is JSON, else raw text), :body-text (raw text), :headers |
:rf.http/decode-failure |
A 2xx response whose body the decoder rejected. | :body-text, :cause (the message), :schema-validation-failure?; :reason :too-many-keys and :limit when the key cap was exceeded |
:rf.http/accept-failure |
:accept returned {:failure user-map}, threw, or returned anything but a map with exactly one of :ok / :failure. |
:decoded (the body before :accept); :detail is user-map, {:rf.http/bad-accept :threw :message …} or {:rf.http/bad-accept :malformed-return :returned …} |
:rf.http/aborted |
Aborted via :request-id, :abort-signal, or the destruction of the actor or frame that issued it. |
:reason, :actor-id; :message on some paths |
- The status is classified before the body is decoded, so a 4xx or 5xx response never runs
:decode. Its raw text is on the failure map's:body-text, and its:bodyis that text parsed, keys as keywords, when the Content-Type is JSON (jsonor a+jsonsuffix), else the text itself. The parse is best-effort: a body that does not parse, or exceeds the key cap, stays the raw string, and the kind is still:rf.http/http-4xx/:rf.http/http-5xx. An empty 2xx JSON body decodes tonilrather than failing. - The first four kinds are the ones
:retry :onaccepts, beside the statuses from 400 to 599 a 4xx or 5xx failure carries at:http-status.:rf.http/decode-failure,:rf.http/accept-failureand:rf.http/abortedare never retried. - Every failure map also names the request it came from:
:request {:method :url}(the method sent,:getwhen the request set none),:request-id,:attempt,:max-attempts(when a retry policy was set) and:work/id. - Resources and mutations store this same map as their
:error(and a resource's:refresh-error), so onecaseon:kindserves both.
Failures are a closed set explains the kinds in the guide.
Request interceptors¶
Register an interceptor to change every request a frame issues: add an auth header, stamp a request id, log timings. Define it once at the top level with rf/reg-http-interceptor, then turn it on for a frame by naming its id in that frame's :http-interceptors config. Remove a definition with (rf/clear :http-interceptor id). The facade has no clear-http-interceptor; re-frame.http.managed/clear-http-interceptor below is the function behind it. Interceptors: stamp every request once walks through the common cases.
reg-http-interceptor¶
- Kind: macro
- Signature:
- Description: Registers an interceptor definition for
:rf.http/managed: its:beforefn can rewrite each outgoing request, and its:afterfn each reply. The definition belongs to no frame; it runs only for a frame that namesidin its:http-interceptorsconfig.interceptor-mapcarries at least one of:before (fn [ctx] ctx')and:after (fn [ctx response] response'), plus the standard:rf/registration-metadatakeys.- A
:beforefn receives a ctx{:request … :args … :frame … :event … :sensitive? …}and returns it, possibly changed.:sensitive?istruewhen the args marked the request sensitive, at the top level or under:request; the:requestleft at the end of the chain is what is sent. An:afterfn receives that final ctx and the reply map, so it can match a response to its request, and returns the reply. :beforefns run in the order the frame's:http-interceptorsvector names them, before the request goes to the platform HTTP client.:afterfns run in reverse of that order, after the reply is built and before it is dispatched. The reply then goes to:on-successwhen the final reply's:statusis:ok, and to:on-failureotherwise.:beforefns run once per request, not per retry attempt: every attempt sends the request the chain produced.:afterfns run once, on the final reply, including a:cancelledone.- A request uses the chain as it stood when the request was issued, for both halves and every retry. Registering, replacing or clearing an interceptor, or re-making the frame with a different
:http-interceptors, affects only requests issued afterwards. - A
:beforecan mark a request sensitive by setting[:request :sensitive?] true. - Registration reads no frame: call it at the top level, at namespace load, like any other
reg-*. Load order configures nothing; a frame's:http-interceptorsvector is the whole chain and its order. A frame that names no chain runs no interceptor, and a definition no frame names is unused. - The frame's ids resolve through its own registrations when a request is issued, so a later image's definition of an id shadows the app's for frames built on that image. Frames diverge by naming different ids.
- Re-registering an existing id replaces its definition; every frame naming it runs the new one from its next request.
- Errors:
- At registration:
:rf.error/http-bad-interceptor, for an invalid shape, such as a non-keyword id, neither:beforenor:after, or a non-fn slot. A:framekey raises it too, with a message naming:http-interceptors, since a definition belongs to no frame. - At
make-frame::rf.error/http-bad-interceptor, when:http-interceptorsis not a vector of keywords. - When a request is issued:
:rf.error/unregistered-interceptor, when the frame names an id noreg-http-interceptordefines. It names the id, and the request is not sent. - When a request runs. A failing
:beforemeans the request is not sent, and a failing:aftermeans the reply is not delivered::rf.error/http-interceptor-failed: a:beforeor:afterthrew. Carries:frame,:interceptor-id,:urland:cause, plus:phase :afterwhen an:afterthrew.:rf.error/http-interceptor-bad-return: a:beforeor:afterreturned something other than a map. Carries:idand:returned.
- At registration:
- Example:
(rf/reg-http-interceptor :auth/inject {:before (fn [ctx] ;; read the token fresh on each request, so a rotated token is picked up (let [token (-> (rf/app-db-value (:frame ctx)) :auth :token)] (cond-> ctx token (assoc-in [:request :headers "Authorization"] (str "Bearer " token)))))}) ;; Or with both sides — :before stamps a start mark, :after reads it. (rf/reg-http-interceptor :telemetry {:before (fn [ctx] (assoc ctx ::started (js/Date.now))) :after (fn [ctx resp] (assoc resp :elapsed-ms (- (js/Date.now) (::started ctx))))}) ;; The frame names its chain, in order. (rf/make-frame {:id :rf/default :http-interceptors [:auth/inject :telemetry]})
re-frame.http.managed/clear-http-interceptor¶
- Kind: function
- Signature:
- Description: Removes the interceptor definition
id. Application code calls it through the facade, as(rf/clear :http-interceptor id).- A definition belongs to no frame, so clearing it removes it for every frame at once. A frame that still names the id fails its next request at issue with
:rf.error/unregistered-interceptor, as for an id never registered. - To stop one frame running an interceptor, re-make that frame without the id in its
:http-interceptors.
- A definition belongs to no frame, so clearing it removes it for every frame at once. A frame that still names the id fails its next request at issue with
- Errors:
:rf.error/registrar-clear-bad-request: through the facade,(rf/clear :http-interceptor id opts)with any opts map, since the clear takes no frame.
- Example:
Privacy and classification¶
Four declarations control what managed HTTP redacts from traces, off-box records and SSR payloads; there is no function for adding names to the denylists at runtime. Keeping secrets out of the trace and Keep secrets out of traces explain the model end to end.
| Declaration | What it covers | Where declared |
|---|---|---|
| Built-in header denylist | A fixed set of always-sensitive header names (Authorization, Proxy-Authorization, Cookie, Set-Cookie, X-API-Key, X-Auth-Token, X-Session-Token, X-CSRF-Token, X-XSRF-Token, Authentication, WWW-Authenticate, Proxy-Authenticate), redacted in the :headers slot of every :rf.http/* trace regardless of :sensitive?. Case-insensitive; no frame can remove a name. |
framework default |
| Built-in query-param denylist | A fixed set of always-sensitive query-param names (api_key, apikey, api-key, access_token, accesstoken, auth, auth_token, authtoken, key, token, secret, password, passwd, session, session_id, sessionid, signature, sig, hmac). The value is redacted inline in :url slots (?api_key=:rf/redacted&page=2), keeping the name and position. A hit also stamps :sensitive? true on the trace event, since the name alone is the signal. |
framework default |
| Managed-HTTP carriers | App-specific sensitive names, declared on the :rf.http/managed reg-fx registration. :headers is a vector of names added to the built-ins, never a policy map, since the header built-ins cannot be removed. :query-params is a vector of names to add, or an {:include […] :except […]} policy map with effective policy (defaults − except) ∪ include; :except drops a built-in name from this app's own dev trace. Names are case-insensitive. The block is checked when a request reads it, not at registration, so a malformed block fails each request with :rf.error/bad-classification (see the :rf.http/managed errors). |
reg-fx :rf.http/managed :carriers {:headers […] :query-params […]} |
Per-request :sensitive? |
Redacts one request's body, params and all URL param values. | the :rf.http/managed args map (:sensitive? at top level, or under :request) |
;; managed-HTTP carrier extensions (union onto the immutable built-ins)
(rf/reg-fx :rf.http/managed
{:carriers {:headers ["X-Honeycomb-Team"]
:query-params ["shop_token"]}}
re-frame.http.managed/managed-handler)
;; per-call opt-in for a single sensitive request
(rf/reg-event :api/login
(fn [_ [_ creds]]
{:fx [[:rf.http/managed
{:request {:method :post :url "/auth/login" :body creds}
:sensitive? true
:on-success [:api/logged-in]
:on-failure [:api/login-failed]}]]}))
Response-body classification¶
The denylists and the :sensitive? flag cover what the request carries. A response body is classified by :sensitive? / :large? props on the slots of the request's :decode schema, which already describes the body's shape. These props apply whether or not the request sets :sensitive?.
(rf/reg-event :auth/login
(fn [_ [_ creds]]
{:fx [[:rf.http/managed
{:request {:method :post :url "/auth/login" :body creds}
;; [:token] redacts; [:user-id] rides verbatim
:decode [:map
[:token {:sensitive? true} :string]
[:user-id :int]]
:on-success [:auth/logged-in]
:on-failure [:auth/login-failed]}]]}))
- A
:sensitive?slot is redacted to:rf/redactedand a:large?slot is replaced with the size marker; a slot carrying both is treated as sensitive. Unmarked siblings are traced verbatim. A prop on the root classifies the whole body, for example[:string {:sensitive? true}]for a response that is an opaque token. - Only a Malli schema in the raw EDN vector form
[op props? …]has per-slot marks the walker can read. Any other:decode(a keyword mode such as:jsonor:text, a custom decoder fn, a registry-keyword ref, a compiledm/schemaobject) leaves the body's shape unknown, so the body is omitted from off-box records entirely rather than shipped raw. - Error bodies are always omitted from off-box records, whatever
:sensitive?says: a 4xx/5xx:bodyand:body-text, and a decode-failure:body-text, are bodies no schema has classified, and error bodies often echo request context or tokens.
Classification does not propagate — declare each surface a secret crosses
A token in the response body, classified by the :decode schema, and the same token stored in app-db need two declarations, because nothing carries one to the other. When the reply handler writes the token into app-db, classify that path too: return :sensitive [[:auth :token]] alongside :db from the reg-event handler (see Classify a durable secret in app-db and the effect map's :sensitive key in re-frame.core). Never copy a secret into an app-db path you have not classified, such as a JWT duplicated at [:auth :user :token]: the copy ships raw until that path is classified or the duplicate is removed.
re-frame.http.managed/managed-handler¶
- Kind: function
- Signature:
- Description: The
:rf.http/managedfx handler. It is public so that an app can re-register:rf.http/managedwith a:carriersblock, as in the carriers example above. Pass it toreg-fx; do not call it from app code.
Testing without a network¶
re-frame.http.stub-transport answers managed HTTP without a network, for tests and demos. A stub transport replaces only the host send — Fetch in the browser, java.net.http.HttpClient on the JVM — so every request still runs the real pipeline: the :before and :after interceptors, status classification, :decode, :accept, retry and backoff, timeouts, the privacy scrub, supersession and abort. Its replies carry every key listed under Reply shape. It ships in the same artefact, day8/re-frame2-http, and is not on the re-frame.core facade. Testing without a network and Answer the HTTP show it in a test.
A response, wherever these functions take one, is a map:
:status— defaults to 200.:status-textand:headersare optional.:body— a string is sent verbatim. Any other value is JSON-encoded, withContent-Type: application/jsonunless:headersnames a content type, and is decoded as a server's body would be: object keys arrive as keywords and keyword values as strings. A:decodeschema coerces them back.:body-binary— replaces:bodyfor a binary read.:delay-ms—route-transportonly: this answer waits that long.
An HTTP error is a response with its status: {:status 503} fails as :rf.http/http-5xx, with the body text on the failure's :body. {:failure {:kind :rf.http/transport}}, or :rf.http/timeout, is a network failure instead of a response.
A request is keyed by the method and the URL it goes out on: after the :before interceptors, with any :params merged in as a query string, so a request carrying :params {:page 2} to /api/todos is keyed [:get "/api/todos?page=2"].
A frame made with the :test or :story preset sets :rf.http/stub-only? true, so its requests never reach the network: one that no stub transport answers fails as :rf.http/transport, with a message naming with-transport and install-transport!.
re-frame.http.stub-transport/route-transport¶
- Kind: function
- Signature:
- Description: A transport that answers each request from
routes.routesis a route map,{[<method> <url>] response-or-fn}. A route's value is a response, or(fn [wire-request] response). A request no route matches fails as:rf.http/transport, naming its method and URL.routesmay instead be one(fn [wire-request] response)that answers every request: a fake backend that routes for itself.wire-requestis the attempt as the host would send it,{:method :url :headers :body :timeout-ms}, with the body encoded.optstakes:delay-ms, how long each answer waits, so a demo's loading states show. A response's own:delay-mswins. With no delay the answer is inline: thedispatch-syncthat issued the request has its reply before it returns.
- Example:
re-frame.http.stub-transport/pending-transport¶
- Kind: function
- Signature:
- Description: A transport that holds every request until the caller settles it, for in-flight, abort and late-completion tests.
tis the transport, andaan atom of the exchanges it has received, in issue order, each{:request wire-request :respond! f :fail! f :cancelled? f}.(respond! response)answers the request with a response map;(fail! failure)fails it with{:kind :rf.http/transport}or{:kind :rf.http/timeout}. Each returns whether it settled the request. Once the request has been answered, aborted or timed out, they deliver nothing and returnfalse, so a test can answer an aborted request late and see the answer fenced.(cancelled?)istrueonce the request was aborted or timed out.- An answer given from test code, outside any event, is dispatched like any reply, so wait for it (
poll-until) before asserting on what it changed.
- Example:
re-frame.http.stub-transport/with-transport¶
- Kind: function
- Signature:
- Description: Sends every
:rf.http/managedrequest issued whilethunkruns throughtransport. The test scope.- The transport is captured when the request issues, so its retries, and an answer that arrives after the scope has exited — a delayed route, a held exchange answered later — still go through it.
- A request is in the scope only if it issues while
thunkruns, so issue requests withdispatch-syncinside it. - An inner scope shadows an outer one, and a scope wins over a frame's installed transport.
re-frame.http.stub-transport/install-transport!¶
- Kind: function
- Signature:
- Description: Sends every
:rf.http/managedrequestframeissues throughtransportuntil the frame is destroyed: a demo's fake backend.frameis a frame id or a live frame value.niluninstalls it. Awith-transportscope still wins for the requests issued inside it. - Example:
Trace events¶
:operation |
:op-type |
When |
|---|---|---|
:rf.http/issued |
:info |
Once per issued request, inside the issuing fx handler, before any supersession or attempt. Carries :rf.reply/work-id (the attempt-1 work id), :rf.reply/work-kind :http, :request-id, :url, :method, :frame, and :reply-to (each branch's target event-id). |
:rf.http/retry-attempt |
:info |
Per intermediate attempt that matched :retry :on. Carries :request-id, :url, :attempt, :max-attempts, :failure, :next-backoff-ms and :recovery: a backoff and :retried on an intermediate row, nil and :no-recovery on the final row. |
:rf.http/replied |
:info |
The completion row (success or failure), built from the reply map before it is dispatched. Identity facts (:status, :rf.reply/work-id, :attempt, :completed-at) are verbatim; the wire-bearing slots (:value / :error / :meta) go through the trace elider and the header denylist. |
:rf.http/<kind> |
:error |
A failure other than an abort, keyed by its :kind (:rf.http/timeout, :rf.http/http-5xx, …). Carries the redacted failure map. |
:rf.http/aborted |
:info |
An abort, whatever its :reason (:user, :request-id-superseded, :actor-destroyed, :frame-destroyed, :epoch-restored, …). Carries :kind, :request-id, :reason, :actor-id, :url. |
:rf.http/stale-suppressed |
:info |
An app reply was suppressed (supersession, obsolete actor target, epoch restore, frame destroy). Carries :rf.reply/status :stale, :rf.reply/work-status :suppressed, :rf.reply/work-id, :rf.reply/carried / :rf.reply/current, :rf.reply/stale-reason and :recovery. :recovery names the trigger (:superseded-by-fresh-request, :actor-destroyed-target-obsolete, :suppressed-on-epoch-restore, :suppressed-on-frame-destroy); :rf.reply/stale-reason is :rf.http/actor-destroyed-target-obsolete for an obsolete actor target and :rf.http/request-id-superseded for the other three. |
:rf.http/aborted-on-actor-destroy |
:info |
One per request cancelled because the actor that spawned it was destroyed. Carries :request-id, :actor-id, :url. |
:rf.warning/http-header-invalid |
:warning |
Per request header the platform's header builder rejects, such as an empty name or a value carrying \r or \n. That header is left out and the request goes on with the rest. Carries :url, :header, :cause; never the value. |
:rf.http/cljs-only-key-ignored-on-jvm |
:warning |
JVM only, per occurrence: the request carried a key the JVM transport ignores (:mode, :cache, :referrer, :integrity or :credentials in :request, or :abort-signal). The request proceeds without it. Carries :key, :url. |
:rf.http/binary-decode-degraded-on-jvm |
:warning |
JVM only, per request with an explicit :decode of :blob, :array-buffer or :form-data: the body arrives as a byte[] rather than the browser object. Carries :decode, :url. |
:rf.error/http-reply-tail-failed |
:error |
In every build: delivering the reply threw after the transport completed (an :after, the reply target, or the completion cascade). There is no retry and no re-send; the reply is not delivered. |
:rf.http.interceptor/registered |
:info |
A reg-http-interceptor succeeded. Carries :id. |
:rf.http.interceptor/cleared |
:info |
(rf/clear :http-interceptor id) removed an existing definition. Carries :id. |
:rf.error/http-interceptor-failed |
:error |
An interceptor's :before or :after threw. Carries :frame, :interceptor-id, :url, :cause, plus :phase :after when an :after threw. The request is not sent (:before) or the reply is not delivered (:after). |
:rf.error/http-interceptor-bad-return |
:error |
An interceptor's :before or :after returned something other than a map. Carries :id, :returned. The request is not sent (:before) or the reply is not delivered (:after). |
Framework integration¶
Not for application code. The framework's own tests reach these across a namespace boundary; they are public for that reason only, at the implementation tier, and may change without notice.
re-frame.http.managed/clear-all-in-flight!— aborts every in-flight request, then empties the registry.re-frame.http.managed/in-flight-snapshot— the in-flight requests keyed by request id, for every frame or for one frame.re-frame.http.managed/actor-in-flight-snapshot— the in-flight requests an actor issued, keyed by actor id.re-frame.http.managed/seed-in-flight-for-test!— records a fabricated in-flight request in the one registry real requests are filed in, so every snapshot and abort path sees it.re-frame.http.managed/abort-on-actor-destroy— aborts the requests an actor issued; the actor-destroy cascade calls it.re-frame.http.managed/clear-all-http-interceptors!— removes every interceptor definition.re-frame.http.managed/interceptors-snapshot— with no argument, every interceptor definition keyed by id; with a frame id, the chain a request from that frame would capture, in order.
See also¶
- re-frame.resources — cached reads and mutations that issue their requests through
:rf.http/managed. - re-frame.core —
:rf.http/managedin the standard fx table, the effect map's:sensitivekey, and the instrumentation and egress functions (project-egress, the observability-sink registration). - re-frame.schemas — the
:schemaregistration key and per-slot:sensitive?/:large?schema props. - Test a pipeline run — stub transports with
dispatch-syncandpoll-until. - Interceptors and secrets — interceptors and trace redaction in the guide.