Skip to content
brought to you byVoidZero

Fetch Client ​

Imported from "void/client".

fetch(path, options?) ​

Type-safe fetch client for calling your API routes from client code, built on top of ofetch. Route paths and return types are inferred from the generated RouteMap.

ts
import { fetch } from 'void/client';

// Types are fully inferred from your route handlers
const users = await fetch('/api/users');
const user = await fetch('/api/users/:id', {
  params: { id: '1' },
});

Signature:

ts
function fetch<P extends keyof RouteMap, M extends MethodsOf<P>>(
  path: P,
  options?: FetchOptions<P, M>,
): Promise<OutputOf<P, M>>;

Options:

OptionTypeDescription
methodstringHTTP method. Defaults to "GET".
bodyunknownRequest body (auto-serialized as JSON).
queryRecord<string, string>Query string parameters.
paramsRecord<string, string>URL path parameters (:id segments).
headersHeadersInitAdditional request headers.
signalAbortSignalAbort signal.
baseURLstringBase URL prepended to the path. Useful for external calls.
retrynumberNumber of retry attempts (ofetch default: 1 for GET).
timeoutnumberRequest timeout in milliseconds.

Returns the parsed JSON response body, or undefined for 204 responses. Throws FetchError on non-2xx responses.

FetchError ​

Error class thrown by fetch on non-2xx responses.

ts
import { fetch, FetchError } from 'void/client';

try {
  await fetch('/api/users/:id', { params: { id: '999' } });
} catch (e) {
  if (e instanceof FetchError) {
    console.log(e.status); // 404
    console.log(e.response); // raw Response
  }
}

Properties:

PropertyTypeDescription
statusnumberHTTP status code.
responseResponseThe raw Response object.
dataunknownParsed response body (if available).

Differences from Native fetch ​

The typed client is built on ofetch with a typed route layer on top. Key differences from native fetch:

BehaviorNative fetchvoid/client fetch
Return typePromise<Response>, so you call .json() yourselfPromise<T>, which auto-parses JSON and returns the typed result directly (undefined for 204)
Error handlingResolves on any HTTP status; you check response.okThrows FetchError on non-2xx responses
URL constructionRaw URL stringRoute path with :param interpolation from options.params + query string from options.query
Body serializationManual JSON.stringify() + Content-Type headerAuto-serializes options.body as JSON and sets Content-Type: application/json
Type safetyAccepts any URL or methodConstrains paths to RouteMap keys and methods to those defined per route. Invalid combinations fail at compile time.
RetryNoneAuto-retries on 408, 429, and 5xx (configurable via retry option)
TimeoutNoneConfigurable via timeout option

headers and signal are passed through to the underlying fetch unchanged.