Skip to content

HTTP Client ​

Introduction ​

When your application talks to another service, you want to write what you mean (a GET with these query parameters, a POST with this JSON body and a token) and get back a response you can inspect without ceremony. @plinthjs/http-client is a small fluent client built on the platform's global fetch. It adds query and body encoding, base URL joining, timeouts, retries with backoff, multipart uploads, request middleware, a concurrent pool, and a fake for tests that never touches the network.

bash
pnpm add @plinthjs/http-client

Making requests ​

Create a client with Http() and call a method named after the HTTP verb. Each one returns a promise of an HttpResponse.

ts
import { Http } from '@plinthjs/http-client'

const response = await Http().get('https://api.example.com/users', { page: 2 })

if (response.successful()) {
  const users = response.json<{ id: number; name: string }[]>()
}

The verbs are get, post, put, patch, delete and head. get and head take query parameters as the second argument; the others take a body. If you need a method outside this list, or want to pass query, body and headers together, use send:

ts
await Http().send('PATCH', 'https://api.example.com/users/1', {
  body: { name: 'Ada' },
  headers: { 'X-Request-Id': 'abc' },
})

Base URLs ​

Give the client a base URL and you can use relative paths. Slashes at the join are handled for you, and a full URL passed to a request is left alone.

ts
const api = Http({ baseUrl: 'https://api.example.com/v1' })

await api.get('/users') // https://api.example.com/v1/users
await api.get('users') // the same
await api.get('https://other.example.com/x') // used as is

You can also set it with the builder: Http().baseUrl('https://api.example.com').

WARNING

A client is a mutable builder. Methods like withToken and withHeaders change the client and return it, so settings accumulate on the same object. Create a fresh Http() for requests that should not share headers, or keep one configured client per remote service and treat it as read only after setup.

Query strings ​

Pass a record as the query. Arrays repeat the key, and null or undefined values are skipped.

ts
await Http().get('https://api.example.com/search', {
  q: 'plinth',
  tags: ['a', 'b'],
  page: 2,
  cursor: null,
})
// GET https://api.example.com/search?q=plinth&tags=a&tags=b&page=2

To add query parameters to every request from a client, use withQuery. Parameters you pass to get are merged on top.

ts
await Http().withQuery({ api_key: 'k' }).get('https://api.example.com/search', { q: 'x' })
// GET https://api.example.com/search?api_key=k&q=x

Sending bodies ​

The body of post, put, patch and delete can be a record, an array or a string. By default a record is encoded as JSON and Content-Type: application/json is set.

ts
await Http().post('https://api.example.com/users', { name: 'Ada' })
await Http().asJson().post('https://api.example.com/users', { name: 'Ada' }) // explicit

Use asForm() for application/x-www-form-urlencoded. Nested values are JSON encoded into the field, and null or undefined fields are left out.

ts
await Http().asForm().post('https://api.example.com/login', { email: 'a@b.co', password: 'x' })
// email=a%40b.co&password=x

A string body is sent as is. To send raw bytes or text with your own content type, use withBody:

ts
await Http().withBody('<note>hi</note>', 'application/xml').put('https://api.example.com/notes/1')

If you set a Content-Type header yourself, the client does not overwrite it.

Uploading files ​

attach(name, contents, filename?, headers?) adds a file part and switches the request to multipart/form-data. The contents can be a string or a Uint8Array. Any body fields you pass to the verb method are sent as ordinary form fields in the same request.

ts
import { readFile } from 'node:fs/promises'

await Http()
  .attach('avatar', await readFile('avatar.png'), 'avatar.png', { 'Content-Type': 'image/png' })
  .post('https://api.example.com/profile', { title: 'My photo' })

When a part has a filename but no Content-Type, application/octet-stream is used. You can attach several files by calling attach more than once, and asMultipart() forces multipart encoding for a request that has only fields.

Headers and authentication ​

ts
const client = Http()
  .withHeaders({ 'X-Request-Id': 'abc' })
  .acceptJson() // Accept: application/json
  .withToken('secret-token') // Authorization: Bearer secret-token
MethodEffect
withHeaders(record)Adds the given headers
withToken(token, type?)Sets Authorization (type defaults to Bearer)
withBasicAuth(user, password)Sets Authorization with Basic credentials
accept(type) and acceptJson()Sets Accept
withUserAgent(ua)Sets User-Agent
withCookies(record)Sends a Cookie header, with values URL encoded
ts
await Http().withToken('abc', 'Token').get('https://api.example.com/me') // Authorization: Token abc
await Http().withBasicAuth('user', 'pass').get('https://api.example.com/me')
await Http().withCookies({ session: 'abc 123' }).get('https://example.com/') // Cookie: session=abc%20123

withCookies does nothing if you already set a Cookie header yourself.

Reading responses ​

An HttpResponse has the body already read, so its accessors are synchronous.

ts
const response = await Http().get('https://api.example.com/users/1')

response.status() // => 200
response.ok() // => true (2xx)
response.successful() // => true (same as ok)
response.failed() // => true for 4xx and 5xx
response.clientError() // => true for 4xx
response.serverError() // => true for 5xx

response.json<{ id: number }>() // parsed JSON (undefined when the body is empty)
response.object() // JSON object, or {} when the body is empty, invalid or not an object
response.text() // the raw body (body() is the same)
response.header('content-type') // => 'application/json' or null
response.headers() // => { 'content-type': 'application/json' }
response.collect() // a collection of the JSON array (or of an object's values)

json() throws when the body is not valid JSON, whereas object() and collect() quietly return an empty result. collect() returns a collection. toResponse() gives you the underlying Response object.

Throwing on failure ​

By default a 4xx or 5xx response is returned, not thrown. Only network errors and timeouts reject. Call throw() when you want a failed response to become an exception. On success it returns the response, so you can chain.

ts
import { HttpRequestError } from '@plinthjs/http-client'

try {
  const user = (await Http().get('https://api.example.com/users/1')).throw().json()
} catch (error) {
  if (error instanceof HttpRequestError) {
    error.message // => 'HTTP request returned status code 404.'
    error.response.status() // => 404
    error.response.json() // the error body
  }
}

There are more precise variants:

ts
response.throwIf(true) // throw (if failed) when the condition holds
response.throwIf((r) => r.status() === 429)
response.throwUnless((r) => r.ok())
response.throwIfStatus(404) // throw when the status is exactly 404
response.throwIfStatus((status) => status >= 500)
response.throwUnlessStatus(201) // throw unless the status is 201

throwIf and throwUnless throw only if the response also counts as failed (4xx or 5xx). throwIfStatus and throwUnlessStatus throw regardless of whether the response failed.

Timeouts ​

timeout(ms) aborts the request when it takes longer than the given number of milliseconds and rejects with an error saying so.

ts
await Http().timeout(5000).get('https://api.example.com/slow')
// rejects: HTTP request to https://api.example.com/slow timed out after 5000ms.

connectTimeout(ms) also takes milliseconds, like timeout. It bounds the time until the response headers arrive (connecting, TLS and the server's first byte) and stops applying once they do, so a long download is never aborted by it. timeout(ms) covers the whole attempt including reading the body.

ts
await Http().connectTimeout(2000).timeout(10_000).get('https://api.example.com/x')

INFO

fetch exposes no separate connection phase, so connectTimeout is a time-to-first-response limit rather than a pure TCP connect limit.

Reusing a client ​

Clients are immutable. Every builder method (withToken, withHeaders, withQuery, timeout, retry, ...) returns a new client and leaves the original untouched, so a shared base client never leaks per-request settings:

ts
const api = Http().baseUrl('https://api.example.com')
await api.withToken(userToken).get('/me') // sends the token
await api.get('/health') // does not

Keep the result of each call: const c = Http(); c.withToken('x') does not change c.

Each retry attempt gets its own timers.

Retrying ​

retry(times, backoff?) retries failed attempts. It retries when fetch throws (a network error or a timeout) and when the response is a 5xx. A 4xx response is never retried, since repeating it would not help.

ts
const response = await Http().retry(3, 100).get('https://api.example.com/flaky')
// up to 4 attempts in total, waiting 100 ms between them

times is the number of retries after the first attempt. The backoff is a number of milliseconds, or a function that receives the retry number (1 for the first retry) and returns milliseconds, so you can back off exponentially:

ts
await Http()
  .retry(4, (attempt) => 2 ** attempt * 100) // 200, 400, 800, 1600 ms
  .get('https://api.example.com/flaky')

When the attempts are used up and the last answer was a 5xx, you receive that 5xx response (so throw() is still available to you). If the last attempt threw, the error is rethrown.

WARNING

Retries re-send the same request. Retrying a POST that is not idempotent can create duplicates, so only retry calls that are safe to repeat, or that carry an idempotency key.

Request middleware ​

beforeSending(callback) registers a function that receives the outgoing request just before it is sent, and may change its url, headers or body. It runs on every attempt, so retried requests are re-signed or re-stamped each time.

ts
await Http()
  .beforeSending((request) => {
    request.headers['X-Request-Time'] = String(Date.now())
  })
  .get('https://api.example.com/users')

You can also pass beforeSending: [...] as an option to Http().

Redirects ​

By default redirects are followed, as fetch does. To stop at the first redirect and handle it yourself:

ts
const response = await Http().withoutRedirecting().get('https://example.com/old')
response.status() // => 301
response.header('location') // the redirect target

maxRedirects(0) does the same. A positive number follows up to that many hops itself and throws TooManyRedirects (exported from @plinthjs/http-client) when the chain is longer. A 303, and a 301 or 302 after a POST, are re-sent as GET without a body, and the Authorization and Cookie headers are dropped when a hop leaves the original origin.

Client options ​

Everything you can set with the builder can also be passed to Http() as options:

ts
const api = Http({
  baseUrl: 'https://api.example.com',
  headers: { Accept: 'application/json' },
  query: { version: 2 },
  timeout: 5000,
  retries: 2,
  retryDelay: 200,
  bodyFormat: 'json', // 'json', 'form' or 'multipart'
})

The options fetch and sleep replace the underlying fetch implementation and the delay used between retries. Both exist mainly so tests can run offline and instantly.

Concurrent requests ​

pool runs many requests at once with an optional cap on how many are in flight. You pass functions that start each request. It resolves to one result per request, in the original order, and never rejects: each result is { status: 'fulfilled', value } or { status: 'rejected', reason }.

ts
import { Http, pool } from '@plinthjs/http-client'

const results = await pool(
  ids.map((id) => () => Http().get(`https://api.example.com/users/${id}`)),
  { concurrency: 5 },
)

for (const result of results) {
  if (result.status === 'fulfilled') {
    console.log(result.value.status())
  } else {
    console.error(result.reason)
  }
}

Without concurrency, every request starts at once. If you would rather get the plain values and have the first failure thrown, use poolValues:

ts
import { poolValues } from '@plinthjs/http-client'

const responses = await poolValues(
  ['a', 'b'].map((id) => () => Http().get(`https://api.example.com/${id}`)),
)
responses.map((response) => response.status()) // => [200, 200]

A failed HTTP status is not a rejection. Only a thrown error (such as a network failure, or throw() inside your function) counts as rejected.

Testing ​

Pass fetch to the client and nothing leaves your machine. FakeHttp provides a fake fetch that returns the responses you script and records every request.

ts
import { FakeHttp, Http } from '@plinthjs/http-client'

const fake = new FakeHttp()
fake.respond(
  { status: 200, body: { id: 1, name: 'Ada' } },
  { method: 'POST', urlContains: '/users' },
)

const client = Http({ fetch: fake.fetch })
const response = await client.post('https://api.example.com/users', { name: 'Ada' })

response.json() // => { id: 1, name: 'Ada' }
fake.lastRequest()?.method // => 'POST'
fake.lastRequest()?.body // => '{"name":"Ada"}'

A response spec has an optional status (default 200), body and headers. A string body is sent as is; any other body is serialized to JSON and gets a JSON content type. The optional second argument limits the response to requests with a given method or a URL containing a given text.

Rules are tried in the order you added them, and the first one that matches wins. A request that matches no rule gets an empty 200 response.

Scripting a sequence ​

sequence returns a different response for each successive call (repeating the last one when it runs out). It is the easiest way to test retries. Pass a no-op sleep so the backoff does not slow your tests.

ts
const fake = new FakeHttp().sequence([{ status: 503 }, { status: 200, body: 'ok' }])
const client = Http({ fetch: fake.fetch, sleep: async () => {} })

const response = await client.retry(1).get('https://api.example.com/flaky')
response.status() // => 200
fake.count() // => 2

For full control, handle takes a function that inspects the recorded request and returns a response spec, or undefined to let a later rule decide:

ts
fake.handle((request) => (request.url.endsWith('/ping') ? { status: 204 } : undefined))

fakeFetch(...handlers) is a shortcut that builds a fake fetch from handlers when you do not need the assertions.

Asserting on what was sent ​

Every request is recorded with its method, url, lower-cased headers and body (as text). Read them from fake.requests, fake.lastRequest() and fake.count(), or assert directly:

ts
fake.assertSent((request) => request.method === 'POST' && request.url.endsWith('/users'))
fake.assertNotSent((request) => request.method === 'DELETE')
fake.assertSentCount(1)
new FakeHttp().assertNothingSent()

The assertions throw an Error with a descriptive message when they fail, so they work with any test runner.

Released under the MIT License.