Your API sent { id: 7 }. Your client called it a User.
@pyreon/http is a fetch client that checks what comes back against your schema, times out by default, encodes path params for you and keeps errors typed. Retries, auth and mocks are plain middleware, and the core has zero dependencies.
bun add @pyreon/http - core
- zero dependenciesMiddleware, schemas, streams and SSR live in their own entries.
- timeout
- on, 30 s
fetchhas none; a hung server never settles the promise. - validation
- any Standard SchemaZod, Valibot, ArkType,
s, or a plain(raw) => T. - native
- endpoints on iOS and AndroidExperimental;
useFetch/useQueryover an endpoint lower to native networking.
- 0 runtime dependencies in the core. Each extra (middleware, schema, mock, SSR, streams) is a separate entry.packages/fundamentals/http/package.json (no dependencies); docs/src/content/docs/http.md 'Everything is optional'
- 30 s default timeout on every request; retry stays off so Query's 3 retries don't become 16 requests.docs/src/content/docs/http.md 'Defaults, and why'
- 28 shared scenarios that the web middleware and the iOS and Android runtimes must answer identically (next release, experimental)..changeset/http-native-client-middleware.md (unreleased)
synthetic · author-run · M3 Max · record of 2026-11-05
Every result, including where we lose →Requests that behave in production.
Responses are checked, not cast
Declare
response: Useronce and every call is validated. A payload that drifts throwsResponseValidationErrorat the boundary instead of crashing a component three screens later. Setvalidate: 'warn'to log and degrade instead.Middleware, not interceptors
(request, next) => response. Retry callsnext()in a loop, refresh re-issues after a 401, a mock returns without callingnext. No__isRetryflags, noeject()handles, order is theusearray.One declaration, three uses
api.endpoint('GET /users/:id', { response: User })is a typed function, a.query()foruseQuerywith its cache key, and a.mutation().paramsis required exactly when the path has placeholders.Safe on a busy server
Clients are immutable (
extend()derives), andrunWithRequestkeeps each SSR render's request inAsyncLocalStorage, so one user's cookie can't reach another user's render.forwardHeadersneeds an allowlist and stops at your origin.
Everything the bare fetch call quietly skips.
A timer for the timeout, string-built URLs, a status check, and a cast that believes anything.
type User = { id: string; name: string }
const ctrl = new AbortController()
const timer = setTimeout(() => ctrl.abort(), 10_000)
try {
const res = await fetch(`https://api.example.com/users/${id}`, { // id = '../admin'?
headers: { Authorization: `Bearer ${token}` },
signal: ctrl.signal,
})
if (!res.ok) throw new Error(`HTTP ${res.status}`) // which errors do we retry?
const user = (await res.json()) as User // trust me
console.log(user.name)
} finally {
clearTimeout(timer)
}Timeout on, params encoded, retry and auth as middleware, the body validated.
import { createHttp } from '@pyreon/http'
import { bearer, retry } from '@pyreon/http/middleware'
import { standardSchema } from '@pyreon/http/schema'
import { z } from 'zod'
const User = z.object({ id: z.string(), name: z.string() })
const api = createHttp({
baseUrl: 'https://api.example.com', // 30 s timeout is already on
use: [bearer(getToken), retry({ limit: 2 })],
schema: standardSchema,
})
const getUser = api.endpoint('GET /users/:id', { response: User })
const user = await getUser({ params: { id } }) // encoded, typed and validatedComing from axios, ky or ofetch?
Interceptors become middleware; the cast becomes a check.
import axios from 'axios'
type User = { id: string; name: string }
const api = axios.create({ baseURL: 'https://api.example.com', timeout: 10_000 })
api.interceptors.request.use((config) => {
config.headers.Authorization = `Bearer ${getToken()}`
return config
})
// retry: a third-party package, or a response interceptor with a flag on config
const { data: user } = await api.get<User>(`/users/${encodeURIComponent(id)}`) // a cast, not a checkaxios has no retry by default, so a 503 throws, and a { id: 7 } body comes back typed as a User. The Pyreon client retries the 503 and throws ResponseValidationError on the bad body.
import { createHttp } from '@pyreon/http'
import { bearer, retry } from '@pyreon/http/middleware'
import { standardSchema } from '@pyreon/http/schema'
import { z } from 'zod'
const User = z.object({ id: z.string(), name: z.string() })
const api = createHttp({
baseUrl: 'https://api.example.com', // 30 s timeout is already on
use: [bearer(getToken), retry({ limit: 2 })],
schema: standardSchema,
})
const getUser = api.endpoint('GET /users/:id', { response: User })
const user = await getUser({ params: { id } }) // encoded, typed and validatedSame fetch-first idea, plus endpoints and schemas.
import ky from 'ky'
type User = { id: string; name: string }
const api = ky.create({
baseUrl: 'https://api.example.com',
retry: 2,
hooks: {
beforeRequest: [({ request }) => request.headers.set('Authorization', `Bearer ${getToken()}`)],
},
})
const user = await api.get(`users/${encodeURIComponent(id)}`).json<User>() // a cast, not a checkky already retries and times out by default. What you gain: params encoding from the path, a declared response schema, typed error bodies, and one endpoint that also feeds useQuery.
import { createHttp } from '@pyreon/http'
import { bearer, retry } from '@pyreon/http/middleware'
import { standardSchema } from '@pyreon/http/schema'
import { z } from 'zod'
const User = z.object({ id: z.string(), name: z.string() })
const api = createHttp({
baseUrl: 'https://api.example.com', // 30 s timeout is already on
use: [bearer(getToken), retry({ limit: 2 })],
schema: standardSchema,
})
const getUser = api.endpoint('GET /users/:id', { response: User })
const user = await getUser({ params: { id } }) // encoded, typed and validatedKeep the defaults you like, add a schema.
import { ofetch } from 'ofetch'
type User = { id: string; name: string }
const api = ofetch.create({
baseURL: 'https://api.example.com',
retry: 2,
timeout: 10_000,
onRequest({ options }) {
options.headers.set('Authorization', `Bearer ${getToken()}`)
},
})
const user = await api<User>(`/users/${encodeURIComponent(id)}`) // a cast, not a checkofetch's onRequest hook becomes bearer(). The response is validated instead of cast, and an abort stays an AbortError, separate from real failures.
import { createHttp } from '@pyreon/http'
import { bearer, retry } from '@pyreon/http/middleware'
import { standardSchema } from '@pyreon/http/schema'
import { z } from 'zod'
const User = z.object({ id: z.string(), name: z.string() })
const api = createHttp({
baseUrl: 'https://api.example.com', // 30 s timeout is already on
use: [bearer(getToken), retry({ limit: 2 })],
schema: standardSchema,
})
const getUser = api.endpoint('GET /users/:id', { response: User })
const user = await getUser({ params: { id } }) // encoded, typed and validatedSend a request through the middleware.
Send a request through real middleware into a mock server. Make the server fail and watch retry() back off; make it hang and the default timeout end it with a TimeoutError; make it return the wrong shape and see ResponseValidationError before your UI does.
const api = createHttp({
schema: standardSchema,
timeout: 3000, // default 30 s, shortened here
use: [retry({ limit: 2 }), mock],
})
const getUser = api.endpoint(
'GET /users/:id', { response: User })The server is @pyreon/http/mock, in this page: no network. The timeout is lowered to 3 s so a hang ends quickly.
- Pick a server behaviour and send the request.
The whole request layer.
createHttp+extend()immutable clients;extendadds headers and middleware and leaves the parent alone.- Shipped middleware
retry(equal-jitter backoff,Retry-After),bearer,refresh,dedupe,logger,forwardHeaders. - Three validation tiers
.json<User>()cast,.json(isUser)guard,.json(UserSchema)with any Standard Schema. - Typed errors
HttpError→ClientError/ServerError, plusTimeoutError,NetworkError,ParseError,ResponseValidationError;AbortErrorkept apart. - Error bodies by status
errors: { 404: NotFound, '5XX': Outage }validates and types the failure body. - Every body encoding
json,form(OpenAPI styles incl.deepObject),multipart, rawbody,cookies. - Lossless JSON
@pyreon/http/jsonkeeps 64-bit ids past 2^53 intact. - Streams
openEventStream(SSE with resume and backoff) andopenNdjsonStream, over POST, with auth and mocks. - Mocks without MSW
createMockis middleware; unmatched requests fall through to the real transport. - Native middlewarenext release
bearer,retryandloggerin a literalusearray lower to iOS and Android with web semantics. Experimental.
Things to build with it.
A mock is middleware, so it can't leak between test files, and unmatched routes fall through.
import { createHttp } from '@pyreon/http'
import { createMock } from '@pyreon/http/mock'
// no MSW, no patched globalThis.fetch: the mock is just middleware
const mock = createMock([
{ path: '/users/1', json: { id: '1', name: 'Ada' } },
{ method: 'POST', path: '/users', status: 201, json: { id: '2', name: 'Grace' } },
])
const api = createHttp({ baseUrl: 'https://api.test', use: [mock.middleware] })
const ada = await api.get('/users/:id', { params: { id: '1' } }).json<{ name: string }>()
await api.post('/users', { json: { name: 'Grace' } })
console.log(ada.name, mock.calls.length) // 'Ada' 2EventSource can't POST, send auth or be mocked. openEventStream can, and break closes the connection.
import { createHttp } from '@pyreon/http'
import { createMock } from '@pyreon/http/mock'
import { openEventStream } from '@pyreon/http/stream'
const sse = 'event: token\ndata: {"text":"Hel"}\n\nevent: token\ndata: {"text":"lo"}\n\nevent: done\ndata: {}\n\n'
const mock = createMock([
{ method: 'POST', path: '/chat', accept: 'text/event-stream', headers: { 'content-type': 'text/event-stream' }, body: sse },
])
const api = createHttp({ baseUrl: 'https://api.test', use: [mock.middleware] })
// a POST with a JSON body, middleware (this mock, or your auth) and headers: none of which EventSource can do
const chat = api.endpoint('POST /chat', { responseType: 'stream' })
const stream = openEventStream(
(ctx) => chat({ json: { prompt: 'Say hello' }, signal: ctx.signal, headers: ctx.headers }),
{ reconnect: false },
)
let reply = ''
for await (const ev of stream) {
if (ev.type === 'done') break
reply += (ev.data as { text: string }).text
}
console.log(reply) // 'Hello'Endpoints feed useQuery directly, and a mutation invalidates every query of the list endpoint.
import { createHttp } from '@pyreon/http'
import { standardSchema } from '@pyreon/http/schema'
import { For } from '@pyreon/core'
import { useMutation, useQuery } from '@pyreon/query'
import { s } from '@pyreon/validate'
const Todo = s.object({ id: s.number(), title: s.string() })
const api = createHttp({ baseUrl: 'https://app.example.com/api', schema: standardSchema })
const listTodos = api.endpoint('GET /todos', { response: s.array(Todo) })
const addTodo = api.endpoint('POST /todos', { response: Todo })
function Todos() {
const todos = useQuery(() => listTodos.query()) // key, fn and type from one line
const add = useMutation({
mutationFn: (title: string) => addTodo({ json: { title } }),
invalidates: [listTodos.key.prefix], // every listTodos query refetches
})
return (
<>
<button onClick={() => add.mutate('Ship it')}>Add</button>
<ul>
<For each={() => todos.data() ?? []} by={(t) => t.id}>
{(t) => <li>{t.title}</li>}
</For>
</ul>
</>
)
}A small core and opt-in entries.
Every export has a reference page with its signature, an example and the mistakes people make with it.
- createHttp
- defineEndpoint
- compose
- createFetchTransport
- fetchTransport
- RequestError
- HttpError
- ClientError
- ServerError
- TimeoutError
- AbortError
- NetworkError
- ParseError
- ResponseValidationError
- isAbortError
- buildUrl
- applyPathParams
- buildQuery
- encodeForm
- encodeMultipart
- encodeCookies
- retry
- bearer
- refresh
- dedupe
- logger
- forwardHeaders
- standardSchema
- createMock
- runWithRequest
- openEventStream
- openNdjsonStream
- losslessJson
- toQueryOptions
- encodePathParam
Good to know before you start.
No cache, on purpose
Caching, dedup and retries-by-default belong to @pyreon/query, which calls this client. Retry here is opt-in so the two don't multiply.
Use params, never a template string
Building the path with a template string skips encoding, so an id of ../admin reaches /admin. Write api.get('/users/:id', { params: { id } }); the pyreon/no-unencoded-path-interpolation lint rule flags the other form.
Bearer tokens stay on your origin
bearer and forwardHeaders only attach to requests on baseUrl's origin unless you pass { crossOrigin: true }.
.mutation() and strict optional types
Today useMutation(endpoint.mutation({ invalidates })) fails to typecheck with exactOptionalPropertyTypes (on in Pyreon's preset). Pass { mutationFn, invalidates: [endpoint.key.prefix] } instead, as in the recipe below.
What people ask first.
How fast is it?
The record has a head-to-head with ofetch, ky, redaxios and axios, but its harness changed after that run (a new 'library defaults' row, PR #4142), so we are not quoting it here until the next measured run. The bench/ file is in the repo.
Why is retry off?
Because @pyreon/query already retries three times, so a failing query makes four attempts. A client that also retried three times would send four requests per attempt: sixteen in all. Add retry() where you call the client directly.
Does it run on the server?
Yes, on Node, Bun and edge runtimes with fetch. @pyreon/http/server is the only entry that touches node:async_hooks, so it never lands in a browser bundle.
What about iOS and Android?
The imperative client is web and server. Same-file endpoints called through useFetch or useQuery lower to the native networking runtime, and bearer, retry and logger middleware cross too (next release). Native is experimental.
Trust the network a little less. Your types a little more.
bun add @pyreon/http