HTTP Client
Effect 4 ships three stacked layers: a fully typed HTTP client (request as value, Schema-decoded response, built-in retries), a low-level server (router as Layer, middleware as function), and HttpApi — a schema-first API description that derives a server, a typed client, and OpenAPI/Swagger/Scalar docs from one definition, with the contract checked end-to-end at compile time.
Four cooperating modules: HttpClient is the service you acquire and decorate with policy; HttpClientRequest is an immutable request built with pipes; HttpClientResponse decodes a raw response through a Schema; HttpClientError is the tagged error family for transport/status/body failures. Composing a schema decoder also adds SchemaError. Idiomatic use: wrap the union in a domain service so callers never touch headers.
Official example: Effect's release-matched
ai-docsHttpClient example builds a typed client service.
HttpClient
effect/http/HttpClient — unstable
A service (HttpClient.HttpClient) representing the ability to execute an HTTP request. Acquire from context, decorate with policy, execute requests. Decorators (mapRequest, filterStatusOk, retryTransient, followRedirects, withRateLimiter) return a new client with that behavior baked in — configure once, every call inherits it.
Mental model. Middleware-wrapped fetch in the Effect world. The base implementation comes from a Layer (FetchHttpClient.layer, NodeHttpClient, or BunHttpClient) — never constructed directly. Convenience methods client.get/.post/.execute return Effect<HttpClientResponse, HttpClientError>.
Self-contained source · Type-checked
import { Context, Effect, flow, Layer, Schedule, Schema } from "effect"
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
HttpClientResponse
} from "effect/http"
// The decoded shape we want callers to receive — an employee record from the HRIS.
class Employee extends Schema.Class<Employee>("Employee")({
id: Schema.Int.check(Schema.isGreaterThan(0)),
name: Schema.String,
level: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })),
baseSalary: Schema.Finite
}) {}
// One wrapper error so callers see a single failure type, not the raw zoo.
class HrisError extends Schema.TaggedError<HrisError>()(
"HrisError",
{ cause: Schema.Defect() }
) {}
class Hris extends Context.Service<Hris, {
readonly allEmployees: Effect.Effect<ReadonlyArray<Employee>, HrisError>
getEmployee(id: number): Effect.Effect<Employee, HrisError>
recordRaise(raise: Omit<Employee, "id">): Effect.Effect<Employee, HrisError>
}>()("comp/Hris") {
static readonly layer = Layer.effect(
Hris,
Effect.gen(function*() {
// Acquire the base client and decorate it with policy, ONCE.
const client = (yield* HttpClient.HttpClient).pipe(
HttpClient.mapRequest(flow(
HttpClientRequest.prependUrl("https://hris.acme.internal"),
HttpClientRequest.acceptJson
)),
HttpClient.filterStatusOk, // fail unless the status is 2xx
HttpClient.retryTransient({ // network/timeouts + 408/429/500/502/503/504
schedule: Schedule.exponential(100),
times: 3
})
)
const allEmployees = client.get("/employees").pipe(
Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Array(Employee))),
Effect.mapError((cause) => new HrisError({ cause })),
Effect.withSpan("Hris.allEmployees")
)
const getEmployee = Effect.fn("Hris.getEmployee")(function*(id: number) {
yield* Effect.annotateCurrentSpan({ id })
return yield* client.get(`/employees/${id}`, { urlParams: { format: "json" } }).pipe(
Effect.flatMap(HttpClientResponse.schemaBodyJson(Employee)),
Effect.mapError((cause) => new HrisError({ cause }))
)
})
const recordRaise = Effect.fn("Hris.recordRaise")(function*(
raise: Omit<Employee, "id">
) {
return yield* HttpClientRequest.post("/raises").pipe(
HttpClientRequest.bodyJsonUnsafe(raise),
client.execute,
Effect.flatMap(HttpClientResponse.schemaBodyJson(Employee)),
Effect.mapError((cause) => new HrisError({ cause }))
)
})
return Hris.of({ allEmployees, getEmployee, recordRaise })
})
).pipe(
// Choose the implementation here. Swap to NodeHttpClient/BunHttpClient freely.
Layer.provide(FetchHttpClient.layer)
)
}HttpClient.get (runs immediately) and HttpClientRequest.get (builds a value) are two paths to the same result — the request-value path gives more control. Every decorator is a pure transform, so you can derive multiple specialized clients from one base. Requests carry a span, so retries and timings appear in tracing automatically.
| Decorator | What it does |
|---|---|
mapRequest / mapRequestEffect | Transform every outgoing request (prepend base URL, add auth, set headers). |
filterStatusOk / filterStatus | Turn non-2xx (or a custom predicate) into a StatusCodeError. |
retry / retryTransient | Retry on a Schedule; retryTransient covers transport/timeouts and 408, 429, 500, 502, 503, 504. |
followRedirects | Chase 3xx responses up to a hop limit. |
timeout | Fail a request that has no response within a duration, as an HttpClientError the retry decorators treat as transient; see below. |
withRateLimiter | Throttle outgoing requests through a RateLimiter — handy to stay under API quotas. |
tap / tapRequest / tapError | Observe requests/responses/errors without changing them. |
catch / catchTag / catchTags | Recover inside the client: both overloads of catch require the handler to produce another HttpClientResponse. To recover to any other value, use Effect.catch on the result of client.execute(request). |
transformResponse | Wrap every response Effect, for policies no dedicated decorator covers. |
withCookiesRef | Maintain a cookie jar in a Ref<ReadonlyArray<Cookie>>: response cookies are merged per response URL, and each request gets the cookies matching the host, path, and scheme of its final URL — after later prependUrl transforms or an HttpApiClient baseUrl, and again on every redirect hop when followRedirects is applied after it. |
withScope | Tie every request the client sends to the caller's Scope, so a response body or socket stays open until that scope closes; see below. |
withCircuitBreaker | Stop calling an origin that keeps failing; see below. Experimental. |
HttpClient.isTransientError(error) and HttpClient.isTransientResponse(response) are the predicates retryTransient uses (timeouts, TransportError, and the transient statuses), exported for custom retry policies and circuit classifiers.
Migration: withCookiesRef takes Ref<ReadonlyArray<Cookies.Cookie>> instead of Ref<Cookies>. Seed it with Cookies.mergeIntoArray, or with cookies that set a domain; a host-less cookie in the seed is never sent.
withRateLimiter can learn limits and reset delays from response headers and automatically retry HTTP 429 responses. Those 429 retries are unlimited by default: set times to a finite production budget, or times: 0 to return/fail on the first 429. responseHeaders remaps non-standard limit/remaining/reset/retry header names. disableResponseInspection disables adaptive updates and header delays, but deliberately does not disable the 429 retry loop.
followRedirects defaults to at most ten hops and follows Fetch-style method changes: POST becomes GET for 301/302, and non-GET/HEAD becomes GET for 303. On a cross-origin redirect it strips authorization, proxy-authorization, and cookie before issuing the next request, preventing credentials from leaking to the new origin. When the hop limit is reached it returns the last 3xx response rather than failing; an invalid Location also returns the redirect response unchanged. The next request uses the resolved Location exactly as sent (its query is not re-encoded), a switch to GET also drops the body headers (Content-Encoding, Content-Language, Content-Location), and each discarded redirect body is released. A failure in request preprocessing (a failing mapRequestEffect) does not bypass response-level recovery such as HttpClient.catch when redirects are enabled.
Warning: With
FetchHttpClientthe platformfetchfollows redirects before Effect ever sees them (probed on Node 26: a302arrives as the final200, andresponse.urlreports the final URL).HttpClient.followRedirects— and any per-hop validation you hang on it — only takes over when the underlying fetch is told not to: provideFetchHttpClient.RequestInitwith{ redirect: "manual" }. In a browser a manual redirect is an opaque response, so hop-by-hop control is a server-side technique.
Retries, time budgets, and cancellation
retryTransient honors a valid Retry-After on a response or response-bearing error: integer seconds or an HTTP date, measured against the Effect Clock. Its delay is the maximum of the schedule delay and the server's delay, not an additional sleep; malformed headers (negative, fractional, or exponent values such as 1.5 or 1e3) fall back to the schedule and past dates add no wait. Headers.parseRetryAfter / Headers.retryAfterDelay expose the same parsing. The header does not make a non-transient response retryable or override the schedule/count limit. withRateLimiter also interprets HTTP dates as dates, not seconds.
- Every call gets a finite budget. No client has a timeout until you add one.
HttpClient.timeout("10 seconds")bounds each attempt when placed beforeretryTransientand the whole retry loop, backoff included, when placed after it. An expired request is interrupted (which aborts the transport while it still waits for headers) and fails with anHttpClientErrorwhose reason is aTransportErrorwith aCause.TimeoutErrorcause, so the client keeps the plainHttpClienttype andretryTransientretries it.HttpClient.transformResponse(Effect.timeout(...))bounds the same span but adds a bareCause.TimeoutErrorto the client's error channel instead. - The budget ends when the response arrives. The timer starts after request preprocessing and stops when the wrapped client returns a response — for a plain client, when the headers arrive. Response middleware applied before
timeout(atap, a retry) runs inside the budget, including any body it reads; a body read by the caller (response.json,schemaBodyJson,response.stream) is not covered, so give a large or streamed body its ownEffect.timeout. UnderwithScope, a timeout that fires after the headers have arrived does not abort the connection; it stays open until the scope closes. - Interruption cancels the request, not just the wait. The client hands the platform an
AbortSignaland aborts it when the calling fiber is interrupted — by a timeout, a lost race, or a closed scope (probed: the remote server observes the disconnect). Wrapping a non-Effect SDK yourself? Forward the signalEffect.tryPromisegives you; see the request-cancellation recipe. retryTransientdoes not look at the method. It replays aPOSTas readily as aGET. After a timeout or a dropped connection the first attempt may already have been applied, so retry only requests that are replay-safe: reads, or mutations protected by an idempotency key the server honors. Derive two clients from one base instead of retrying everything.- Retry budgets are finite (
times, or a boundedSchedule), andwithRateLimiter's 429 loop needs its owntimesas noted above.
Self-contained source · Type-checked
import { Effect, flow, Schedule } from "effect"
import { HttpClient, HttpClientRequest } from "effect/http"
export const makeHrisClients = Effect.gen(function*() {
const base = (yield* HttpClient.HttpClient).pipe(
HttpClient.mapRequest(flow(
HttpClientRequest.prependUrl("https://hris.acme.internal"),
HttpClientRequest.acceptJson
)),
HttpClient.timeout("5 seconds"), // per attempt
HttpClient.filterStatusOk
)
// Reads are replay-safe: retry transient faults inside a total budget.
const reads = base.pipe(
HttpClient.retryTransient({ schedule: Schedule.exponential("100 millis"), times: 3 }),
HttpClient.timeout("20 seconds") // whole call, backoff included
)
// Writes are sent once unless the caller supplies the key the HRIS deduplicates on.
const writeOnce = base
const idempotentWrite = (idempotencyKey: string) =>
base.pipe(
HttpClient.mapRequest(HttpClientRequest.setHeader("idempotency-key", idempotencyKey)),
HttpClient.retryTransient({ schedule: Schedule.exponential("200 millis"), times: 2 })
)
return { reads, writeOnce, idempotentWrite } as const
})Response lifetimes and withScope
Without withScope, a request is aborted when its caller is interrupted before the response arrives or while it reads the body, and a response nobody starts reading is aborted once it is garbage-collected (after five seconds on runtimes without FinalizationRegistry). HttpClient.withScope(client) adds Scope to the client's requirements and hands ownership to that scope instead: use it when a response body, an upgraded socket, or a HttpClientResponse.toWeb hand-off must stay open after the response effect has completed, and close it by closing the scope.
- Ownership follows the execution, not the request value. Every request the transport sends while the scoped client executes belongs to the scope — each redirect hop, each retry attempt, each request rewritten by middleware — wherever
withScopesits relative tofollowRedirects,withCookiesRef, orretryTransient. Running the same request value, or the same response effect, concurrently under different scopes gives each execution its own owner. - Closing the scope aborts. Pending requests and open response bodies are aborted when the scope closes, and a request sent after the scope has closed is aborted before the transport starts it. Interrupting a request before its response arrives still aborts it; once the response has been returned, its body is released only by the scope.
- Helper requests are captured too. A request that middleware sends with another client while this one executes — a token fetch inside
mapRequestEffect, say — joins the same scope; with nestedwithScope, the innermost scope owns it. To give such a helper its own lifetime, applywithScopeto the helper client and run its request in its ownEffect.scoped.
Fragment · Type-checked
import { Effect, Stream } from "effect"
import { HttpClient } from "effect/http"
declare const appendToFile: (chunk: Uint8Array) => Effect.Effect<void>
// The connection stays open while the body streams, and is aborted when the scope closes —
// on success, failure, or interruption.
export const downloadExport = Effect.scoped(
Effect.gen(function*() {
const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk, HttpClient.withScope)
const response = yield* client.get("https://hris.acme.internal/exports/payroll.csv")
yield* Stream.runForEach(response.stream, appendToFile)
})
)Migration:
withScopeused to track only the request value passed to it, so redirect hops, retries, and requests rewritten after it could escape the scope. It now owns every request sent during the execution, including requests other clients send from inside its middleware; give those their own scoped client if they must outlive or predate the caller's scope.
Circuit breaking
HttpClient.withCircuitBreaker({ breaker, key?, classify? }) guards each request with a CircuitBreaker and adds CircuitBreakerError to the client's error channel when a circuit rejects a call. Circuits are keyed by request origin unless key says otherwise. The default HttpClient.circuitBreakerClassifier counts transport failures, timeouts, and 408/500/502/503/504 as failures (carrying any Retry-After hint), ignores 429, and counts every other response as success; supply classify to treat, for example, a 200 with an error body as a failure. The same status rules apply whether a status arrives as a response or as a StatusCodeError from filterStatusOk; other errors are ignored. CircuitBreaker.make needs a CircuitBreakerStore (such as CircuitBreaker.layerStoreMemory()) and a Scope. Both APIs are experimental.
Self-contained source · Type-checked
// @effect-diagnostics experimentalApiUsage:off
import { Effect } from "effect"
import { HttpClient } from "effect/http"
import { CircuitBreaker } from "effect/persistence"
export const guardedClient = Effect.gen(function*() {
const breaker = yield* CircuitBreaker.make({
tripPolicy: CircuitBreaker.consecutive(5),
openDuration: "30 seconds"
})
return (yield* HttpClient.HttpClient).pipe(HttpClient.withCircuitBreaker({ breaker }))
})User-controlled destinations
A URL that comes from a user — a webhook target, an "import payroll file from URL" field, an avatar link — turns your server into a proxy for whoever typed it (server-side request forgery). Treat the destination as untrusted input:
- Allow-list scheme and port (
https:only,443or a short list) after parsing withUrl.fromString; reject userinfo (user:pass@host). - Resolve the host and reject non-public addresses: loopback, private ranges, link-local (which includes the
169.254.169.254cloud metadata endpoint), unique-local IPv6, IPv4-mapped IPv6, multicast, and the unspecified address.effect/nethas the predicates. - Re-validate at every hop. A public URL can redirect to an internal one, so disable platform redirects (
redirect: "manual", see the warning above) and run the same check on eachlocation— or do not follow redirects at all. Re-check after DNS resolution too: connect to the address you vetted, or a second lookup can answer differently. - Bound everything else: a short timeout, a response-size cap, no credentials or internal headers on the outgoing request, and a response the caller cannot read verbatim if they should not learn what an internal address answers.
Self-contained source · Type-checked
import { Effect, Schema } from "effect"
import { NetAddress } from "effect/net"
export class ForbiddenDestination extends Schema.TaggedError<ForbiddenDestination>()(
"ForbiddenDestination",
{ reason: Schema.String }
) {}
const isPublicAddress = (ip: NetAddress.IpAddress): boolean =>
!NetAddress.isUnspecified(ip) &&
!NetAddress.isLoopback(ip) &&
!NetAddress.isLinkLocal(ip) && // 169.254.0.0/16 (cloud metadata) and fe80::/10
!NetAddress.isMulticast(ip) &&
(NetAddress.isIpv4Address(ip)
? !NetAddress.isPrivate(ip) // 10/8, 172.16/12, 192.168/16
: !NetAddress.isUniqueLocal(ip) && !NetAddress.isIpv4Mapped(ip))
// `resolvedAddresses` comes from your resolver capability (for example `dns.lookup(host, { all: true })`).
export const assertPublicDestination = Effect.fn("assertPublicDestination")(function*(
url: URL,
resolvedAddresses: ReadonlyArray<string>
) {
if (url.protocol !== "https:" || url.username !== "" || url.password !== "") {
return yield* new ForbiddenDestination({ reason: "scheme or credentials not allowed" })
}
if (resolvedAddresses.length === 0) {
return yield* new ForbiddenDestination({ reason: "host did not resolve" })
}
for (const text of resolvedAddresses) {
const ip = yield* Effect.fromResult(NetAddress.ipFromString(text)).pipe(
Effect.mapError(() => new ForbiddenDestination({ reason: "unparseable address" }))
)
if (!isPublicAddress(ip)) {
return yield* new ForbiddenDestination({ reason: "non-public address" })
}
}
return url
})Reach for it when you call any HTTP service and want retries, decoding, tracing, and a clean domain API instead of raw fetch.
FetchHttpClient
effect/http/FetchHttpClient — unstable
The fetch-backed HttpClient implementation. Provide FetchHttpClient.layer anywhere a client is needed. Works in browsers, serverless, Node, Bun, and Deno. Swap the underlying fetch via FetchHttpClient.Fetch (tests or custom agent); set default RequestInit options via FetchHttpClient.RequestInit.
Self-contained source · Type-checked
import { Effect, Layer } from "effect"
import { FetchHttpClient } from "effect/http"
// Force credentials: "include" on every fetch by layering RequestInit —
// so the HRIS session cookie rides along on each call.
const ClientLayer = FetchHttpClient.layer.pipe(
Layer.provide(Layer.succeed(FetchHttpClient.RequestInit, { credentials: "include" }))
)Per-request method, headers, body, and the abort signal always come from the client and override the same fields in RequestInit; everything else (credentials, cache, redirect, integrity) is yours to set. A bodyStream request is sent as a Web ReadableStream with duplex: "half", and any content-length header is dropped, because fetch computes framing itself. On a runtime whose fetch cannot stream request bodies, a stream body fails with an EncodeError before anything is sent, instead of silently uploading [object ReadableStream]; provide FetchHttpClient.StreamBodyFallback set to "buffer" to collect the stream in memory and send it whole (unsafe for large or unbounded uploads). Support is detected once, on the first stream body, using the global Request. CORS, cookie, redirect, and streaming-upload behavior is otherwise the runtime's, not Effect's, so test uploads on the host you deploy to.
HttpClientResponse.toWeb(response) returns the original Web Response of a fetch-backed response as Some (and None for other backends), so its body can be handed to a platform API such as Cloudflare R2 without copying.
Reach for it when you want the portable, zero-dependency client — which is most of the time. Use NodeHttpClient/BunHttpClient only when you need native streaming or connection-pool control.
HttpClientRequest
effect/http/HttpClientRequest — unstable
An immutable request description built with combinators. Start from a verb (get, post, put, patch, delete, head, options, query) and pipe on URL pieces, query params, headers, auth, and a body. Nothing executes until a client runs it.
HttpClientRequest.query(url) builds an HTTP QUERY request: a safe, idempotent read that carries its query in the body, so the search above could be HttpClientRequest.query("/employees/search") with the same body builder. Clients have a matching client.query(url, options) method and HttpClient.query accessor. Many servers, proxies, and caches do not route QUERY yet, so confirm support on the whole path before switching from POST.
Mental model. A value, not an action — stash, clone, and pass around. Factor out reusable request fragments and apply them per-call or, via HttpClient.mapRequest, to a whole client.
Self-contained source · Type-checked
import { Effect, Redacted } from "effect"
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"
const program = Effect.gen(function*() {
const client = yield* HttpClient.HttpClient
// Search the HRIS for employees in a given comp band.
const request = HttpClientRequest.post("/employees/search").pipe(
HttpClientRequest.prependUrl("https://hris.acme.internal"),
HttpClientRequest.setUrlParams({ page: 1, limit: 20 }), // numbers are coerced
HttpClientRequest.bearerToken(Redacted.make("hris-service-token")),
HttpClientRequest.acceptJson,
HttpClientRequest.bodyJsonUnsafe({ level: 5, departmentId: "ENG" })
)
return yield* client.execute(request).pipe(
Effect.flatMap(HttpClientResponse.filterStatusOk)
)
})Tip: Body builders.
bodyJsonUnsafe(sync, throws on circular data) andbodyJson(effectful, safe) for JSON;bodyText,bodyUint8Array,bodyUrlParams,bodyFormData/bodyFormDataRecordfor the rest;bodyStreamfor streaming uploads;bodyFileto send a file from disk. For type-checked request bodies,schemaBodyJson(MySchema)encodes through a Schema before sending.
Use updateHeaders(f) for a whole-map immutable transform and removeHeader(name) for one field. Replacing a request body also synchronizes its content-type and content-length: metadata supplied by the new body replaces stale values, and an empty or FormData body removes both so the platform can derive the right headers.
Request compression and native connections
compressBody("gzip" | "deflate", { minSize? }) is an effectful request transform using global CompressionStream. The default threshold is 1024 known bytes; unknown-length streams are always compressed. It preserves content type, updates byte-body content length, and removes stream content length. Empty, FormData, raw, below-threshold, and already encoded bodies (even identity) are unchanged. Byte-compression failures are defects, not a new typed error channel; stream failures surface while sending.
Self-contained source · Type-checked
import { HttpClientRequest } from "effect/http"
export const compressed = HttpClientRequest.post("https://api.example.com/import").pipe(
HttpClientRequest.bodyText("employee_id,salary\n".repeat(200)),
HttpClientRequest.compressBody("gzip")
)For client-wide compression use HttpClient.mapRequestEffect(HttpClientRequest.compressBody("gzip")). Retry preprocessing recompresses each attempt: compress a large replayable body once before execute instead. Compression does not make a one-shot stream replayable. Fetch streaming uploads still need runtime support for duplex: "half"; Safari/Firefox support must not be assumed.
NodeHttpClient.makeDispatcherOptions / layerDispatcherOptions accept typed Undici agent options: connect: { socketPath } for Unix sockets (or Windows named pipes), and connect: { ca, cert, key, servername, rejectUnauthorized } for TLS/mTLS. The scoped dispatcher is destroyed on release. URL origin still supplies the Host header/path for Unix connections. BunHttpClient.layerOptions and DenoHttpClient.layerOptions give the same typed Unix-socket and TLS settings through each runtime's native fetch options. NodeHttpClient.layerNodeHttp encodes FormData bodies without loading undici. This is native-transport configuration, not portable Fetch behavior. Per-request Undici timeouts override agent header/body timeouts; use Effect.timeout for application budgets. Never disable certificate verification as a routine fix for a connection error.
Reach for it when a request needs more than a URL, or when you want a reusable request transform.
HttpClientResponse
effect/http/HttpClientResponse — unstable
Typed wrapper around a raw response, plus decoders. schemaBodyJson(schema) reads the body, parses JSON, and validates against a Schema in one effectful step. Transport/body-read/JSON failures are HttpClientError; a value that parses as JSON but violates the schema is SchemaError. schemaJson (decode status + headers + body together) has the same union. Also: filterStatusOk/filterStatus, matchStatus (branch on status code), and stream for incremental consumption.
response.url is the resolved request URL including query parameters and excluding the hash; after redirects it is the final URL, and it is an empty string when the platform cannot tell. Compare its origin with the one you asked for when redirects are allowed; use UrlParams.redactUrl(response.url) before logging it rather than leaking signed query parameters or credentials (URL redaction).
Every decoder takes parse options as a second argument — schemaBodyJson(schema, options), and schemaJson and schemaNoBody honor them too — so { onExcessProperty: "error" } makes an unexpected upstream field a SchemaError instead of a silent drop, and { errors: "all" } reports every issue. The JSON decoders also accept reviver, passed to JSON.parse, for upstreams that need one (for example, reading large integers from the source text).
Mental model. A response is status, headers, and an unread body. Decoders bridge to your domain type — decode failures become typed errors, so a malformed payload can't slip through as any.
Self-contained source · Type-checked
import { Effect, Schema } from "effect"
import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"
const Employee = Schema.Struct({
id: Schema.Int.check(Schema.isGreaterThan(0)),
name: Schema.String
})
const getEmployee = (id: number) =>
Effect.gen(function*() {
const client = yield* HttpClient.HttpClient
const response = yield* client.get(`/employees/${id}`)
// Branch on the status code, decoding each case differently.
return yield* HttpClientResponse.matchStatus(response, {
200: HttpClientResponse.schemaBodyJson(Employee),
404: () => Effect.succeed(null), // not on the HRIS roster
orElse: (res) => Effect.fail(new HttpClientError.StatusCodeError({
request: res.request,
response: res,
description: "Unexpected HRIS response"
}))
})
})Reach for it when you need decoded, validated data or status-aware branching from a response.
HttpClientError
effect/http/HttpClientError — unstable
Tagged error family on the client's error channel. Each carries the request (and often the response) for context:
Key APIs: TransportError, EncodeError, InvalidUrlError, StatusCodeError, DecodeError, EmptyBodyError
Self-contained source · Type-checked
import { Effect } from "effect"
import { HttpClient } from "effect/http"
const safe = Effect.gen(function*() {
// filterStatusOk transforms the CLIENT (adding HttpClientError to its channel),
// so apply it to the client, then make the request.
const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk)
return yield* client.get("https://hris.acme.internal/employees/42")
}).pipe(
// v4 wraps failures in a single HttpClientError; discriminate on reason._tag.
Effect.catchTag("HttpClientError", (e) =>
e.reason._tag === "StatusCodeError"
? Effect.logWarning(`HRIS HTTP ${e.reason.response.status}`)
: Effect.logError("HRIS unreachable", e))
)HttpClient.retryTransient covers transport/timeouts plus statuses 408, 429, 500, 502, 503, and 504 — these are rarely caught by hand solely to implement retry.
An HttpClientError is safe to log: its message and toJSON (and inspection) show the request as its method and redacted URL and the response as its status, never request headers, query values, or bodies. The full request and response remain available as properties, so do not serialize those yourself into logs or client-facing errors.
The URL is redacted with the union of the UrlParams.CurrentRedactedNames in effect where the request executed, where the error was created, and where it is rendered. Names provided around a call therefore still apply when the error is logged later by an unrelated fiber, such as a span exporter or a top-level error reporter, and a body-decoding error created from the response carries them too; a fiber with a shorter list can add redaction but never remove it.
Three failure classes
Keep them distinct all the way to the wrapper error; each one calls for a different response.
| Class | Appears as | What it means | Policy |
|---|---|---|---|
| Transport | HttpClientError with reason._tag "TransportError" (also "InvalidUrlError", "EncodeError" before anything is sent) | no usable response: DNS, connect, reset, abort | retry if the request is replay-safe; otherwise surface "outcome unknown" |
| Status | reason._tag === "StatusCodeError" — only when a filterStatus* decorator is applied | the peer answered, and said no | branch on reason.response.status; most 4xx are permanent, 408/429/5xx may be transient |
| Decode | reason._tag "DecodeError" / "EmptyBodyError" (the body could not be read or parsed), or a separate SchemaError (it parsed but has the wrong shape) | contract drift or a wrong assumption | never retry; alert, and keep the issue path out of user-facing text |
Check the status before decoding the success schema. Without filterStatusOk, a 404 whose body is { "error": "not found" } is fed to schemaBodyJson(Employee) and reported as a schema failure — the one class that looks like your bug instead of the peer's answer. Filter first (on the client, or with HttpClientResponse.filterStatusOk per response), or branch with matchStatus and give each status its own decoder. When you do read an error body, bound it and decode it with its own schema; never echo an upstream error payload to your caller.
Reach for it when you need to distinguish network failures, 404s, and Schema mismatches and handle each differently.