Skip to content
@pyreon/http
fundamentals · requests

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
Documentation
core
zero dependenciesMiddleware, schemas, streams and SSR live in their own entries.
timeout
on, 30 sfetch has 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 / useQuery over an endpoint lower to native networking.
Responses are checked against the schema at the boundary getUser({ params: { id } }) goes out through bearer and retry middleware with the default 30 s timeout. The first response, { id: '7', name: 'Ada' }, passes the User schema and arrives typed. The second, { id: 7 }, fails the check (id must be a string): the call throws ResponseValidationError at the boundary instead of handing a component a value that only claims to be a User. @PYREON/HTTP · CHECKED, NOT CAST getUser() bearer retry server GET /users/7 30 s timeout { id: '7',name: … } { id: 7 } response: User id: z.string() ✓ ✗ const user = await getUser({ params: { id } }) … user: User = { id: '7', name: 'Ada' } typed and validated throws ResponseValidationError at the boundary; err.value holds what arrived no component ever receives { id: 7 } as a User
  • 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 →
why teams pick it

Requests that behave in production.

  1. Responses are checked, not cast

    Declare response: User once and every call is validated. A payload that drifts throws ResponseValidationError at the boundary instead of crashing a component three screens later. Set validate: 'warn' to log and degrade instead.

  2. Middleware, not interceptors

    (request, next) => response. Retry calls next() in a loop, refresh re-issues after a 401, a mock returns without calling next. No __isRetry flags, no eject() handles, order is the use array.

  3. One declaration, three uses

    api.endpoint('GET /users/:id', { response: User }) is a typed function, a .query() for useQuery with its cache key, and a .mutation(). params is required exactly when the path has placeholders.

  4. Safe on a busy server

    Clients are immutable (extend() derives), and runWithRequest keeps each SSR render's request in AsyncLocalStorage, so one user's cookie can't reach another user's render. forwardHeaders needs an allowlist and stops at your origin.

the difference

Everything the bare fetch call quietly skips.

fetch, by hand

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)
}
with @pyreon/http

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 validated
coming from

Coming from axios, ky or ofetch?

Interceptors become middleware; the cast becomes a check.

axios
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 check
Pyreon

axios 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 validated

Same fetch-first idea, plus endpoints and schemas.

ky
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 check
Pyreon

ky 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 validated

Keep the defaults you like, add a schema.

ofetch
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 check
Pyreon

ofetch'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 validated
try it

Send 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.

server
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.

request log
  1. Pick a server behaviour and send the request.
what's included

The whole request layer.

  • createHttp + extend() immutable clients; extend adds 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, plus TimeoutError, NetworkError, ParseError, ResponseValidationError; AbortError kept 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, raw body, cookies.
  • Lossless JSON @pyreon/http/json keeps 64-bit ids past 2^53 intact.
  • Streams openEventStream (SSE with resume and backoff) and openNdjsonStream, over POST, with auth and mocks.
  • Mocks without MSW createMock is middleware; unmatched requests fall through to the real transport.
  • Native middlewarenext release bearer, retry and logger in a literal use array lower to iOS and Android with web semantics. Experimental.
recipes

Things to build with it.

Tests with no network and no MSW

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' 2
Stream an LLM reply over POST

EventSource 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'
A todo list where URL, key and type can't drift

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>
    </>
  )
}
api

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.

client · 5
  • createHttp
  • defineEndpoint
  • compose
  • createFetchTransport
  • fetchTransport
errors · 10
  • RequestError
  • HttpError
  • ClientError
  • ServerError
  • TimeoutError
  • AbortError
  • NetworkError
  • ParseError
  • ResponseValidationError
  • isAbortError
URLs and bodies · 6
  • buildUrl
  • applyPathParams
  • buildQuery
  • encodeForm
  • encodeMultipart
  • encodeCookies
@pyreon/http/middleware · 6
  • retry
  • bearer
  • refresh
  • dedupe
  • logger
  • forwardHeaders
entries: /schema, /mock, /server, /stream, /json, /query · 7
  • standardSchema
  • createMock
  • runWithRequest
  • openEventStream
  • openNdjsonStream
  • losslessJson
  • toQueryOptions
next release · 1
  • encodePathParam
good to know

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.

questions

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
Read the HTTP guide