{"id":50961293,"url":"https://github.com/panoscool/fetch-client","last_synced_at":"2026-06-18T14:31:00.747Z","repository":{"id":365305999,"uuid":"1271512235","full_name":"panoscool/fetch-client","owner":"panoscool","description":null,"archived":false,"fork":false,"pushed_at":"2026-06-16T18:43:22.000Z","size":23,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-06-16T20:25:18.573Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/panoscool.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"buy_me_a_coffee":"panoscool","custom":"https://www.panoscool.com/donate"}},"created_at":"2026-06-16T18:30:33.000Z","updated_at":"2026-06-16T18:43:57.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/panoscool/fetch-client","commit_stats":null,"previous_names":["panoscool/fetch-client"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/panoscool/fetch-client","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/panoscool%2Ffetch-client","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/panoscool%2Ffetch-client/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/panoscool%2Ffetch-client/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/panoscool%2Ffetch-client/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/panoscool","download_url":"https://codeload.github.com/panoscool/fetch-client/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/panoscool%2Ffetch-client/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34495375,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-18T02:00:06.871Z","response_time":128,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-06-18T14:31:00.620Z","updated_at":"2026-06-18T14:31:00.739Z","avatar_url":"https://github.com/panoscool.png","language":"JavaScript","funding_links":["https://buymeacoffee.com/panoscool","https://www.panoscool.com/donate"],"categories":[],"sub_categories":[],"readme":"# @panoscool/fetch-client\n\nA tiny, typed HTTP client built on the native `fetch` API. It adds the ergonomics you usually reach for — a base URL, default and dynamic headers, automatic JSON handling, request/response interceptors, and structured errors — without pulling in a heavy dependency.\n\n## Features\n\n- **Thin wrapper over `fetch`**: No polyfills, no transport magic. Uses the platform `fetch`, `Headers`, and `Response`.\n- **Typed responses**: `client.get\u003cUser\u003e('/me')` resolves to a fully typed `{ data, status, statusText, headers, request, response }`.\n- **Smart bodies**: Plain objects are serialized to JSON with the right `Content-Type`; `string`, `FormData`, `URLSearchParams`, `Blob`, and `ArrayBuffer` pass through untouched.\n- **Flexible response parsing**: `auto` (JSON/text by content type), or force `json`, `text`, `blob`, `arrayBuffer`, `formData`, or `raw`.\n- **Interceptors**: Mutate the outgoing request draft, transform responses, or recover from errors.\n- **Dynamic headers**: Provide static headers or an (async) resolver that sees the finalized request — handy for signing/auth.\n- **Structured errors**: Every failure becomes an `ApiError` with `status`, `data`, `request`, and `response`, plus a redacting `toJSON()` that's safe to log.\n- **Pluggable transport**: Inject a custom `fetch` implementation for testing or advanced control.\n- **ESM \u0026 CJS**: Ships both, with TypeScript types.\n\n## Installation\n\n```bash\nnpm install @panoscool/fetch-client\n```\n\n**Requirements:** Node 20+ (or any runtime with a global `fetch`). The published types rely only on fetch's globals — `@types/node` is enough; you do **not** need the `\"DOM\"` lib in your `tsconfig`.\n\n## Quick start\n\n```typescript\nimport { createApiClient } from '@panoscool/fetch-client';\n\nconst api = createApiClient({ baseUrl: 'https://api.example.com' });\n\ntype User = { id: number; name: string };\n\nconst { data, status } = await api.get\u003cUser\u003e('/users/1');\nconsole.log(status, data.name);\n\nawait api.post('/users', { name: 'Ada' });\n```\n\n### CommonJS\n\n```javascript\nconst { createApiClient } = require('@panoscool/fetch-client');\n```\n\n## Creating a client\n\n```typescript\nconst api = createApiClient({\n  baseUrl: 'https://api.example.com', // optional; prepended to each path\n  headers: { 'x-app': 'web' },        // static headers, or a resolver (see below)\n  transport: createFetchTransport(),  // optional; override the fetch transport\n});\n```\n\n| Option | Type | Description |\n| --- | --- | --- |\n| `baseUrl` | `string` | Prepended to request paths, preserving any base path (e.g. `/v1`). A trailing `/` on the base and a leading `/` on the path are normalized. A path that is itself an absolute URL (`https://…` or `//…`) overrides `baseUrl`. |\n| `headers` | `HeadersInit` \\| `(request) =\u003e HeadersInit \\| Promise\u003cHeadersInit\u003e` | Default headers, or a resolver invoked per request. |\n| `transport` | `ApiTransport` | Custom transport. Defaults to a `fetch`-based transport. |\n\n## Request methods\n\n```typescript\napi.request\u003cTResponse, TBody\u003e(path, options?)\napi.get\u003cTResponse\u003e(path, options?)\napi.post\u003cTResponse, TBody\u003e(path, body?, options?)\napi.put\u003cTResponse, TBody\u003e(path, body?, options?)\napi.patch\u003cTResponse, TBody\u003e(path, body?, options?)\napi.delete\u003cTResponse, TBody\u003e(path, body?, options?)\n```\n\n`options` extends the standard `RequestInit` (so `signal`, `credentials`, `mode`, `cache`, … all pass through), plus:\n\n| Option | Type | Default | Description |\n| --- | --- | --- | --- |\n| `headers` | `HeadersInit` | — | Per-request headers. Override client headers. |\n| `responseType` | `'auto' \\| 'json' \\| 'text' \\| 'blob' \\| 'arrayBuffer' \\| 'formData' \\| 'raw'` | `'auto'` | How to read the response body. |\n\n## The response\n\nEvery successful call resolves to the full response (not just the body):\n\n```typescript\nconst res = await api.get\u003cUser\u003e('/users/1');\n\nres.data;        // parsed body, typed as User\nres.status;      // 200\nres.statusText;  // 'OK'\nres.headers;     // Headers\nres.request;     // the finalized request config (url, method, headers, body)\nres.response;    // the raw Response (body still readable — parsing uses a clone)\n```\n\n## Bodies\n\nPlain objects are JSON-serialized and get `Content-Type: application/json` automatically:\n\n```typescript\nawait api.post('/users', { name: 'Ada' });\n// body: '{\"name\":\"Ada\"}', Content-Type: application/json\n```\n\n`string`, `FormData`, `URLSearchParams`, `Blob`, and `ArrayBuffer`/typed-array bodies are sent as-is, and `Content-Type` is left to the platform:\n\n```typescript\nconst form = new FormData();\nform.set('file', file);\nawait api.post('/upload', form); // no Content-Type forced; boundary handled by fetch\n```\n\n## Response types\n\n```typescript\nawait api.get('/data', { responseType: 'json' });        // res.data: parsed JSON\nawait api.get('/page', { responseType: 'text' });         // res.data: string\nawait api.get('/file', { responseType: 'blob' });         // res.data: Blob\nawait api.get('/buf', { responseType: 'arrayBuffer' });   // res.data: ArrayBuffer\nawait api.get('/form', { responseType: 'formData' });     // res.data: FormData\nawait api.get('/raw', { responseType: 'raw' });           // res.data: Response (unread)\n```\n\nWith `auto` (the default), `application/json` responses are parsed as JSON, everything else as text. A `204 No Content` resolves with `data: null`.\n\n## Headers\n\nPrecedence, from lowest to highest: built-in defaults (`Accept: application/json`) → client headers → per-request headers.\n\nThe client `headers` resolver receives the finalized request (URL, method, serialized body, and headers), which makes request signing straightforward:\n\n```typescript\nconst api = createApiClient({\n  baseUrl: 'https://api.example.com',\n  headers: async (request) =\u003e ({\n    Authorization: `Bearer ${await getToken()}`,\n    'x-signature': sign(request.method, request.url, String(request.body ?? '')),\n  }),\n});\n```\n\n## Interceptors\n\n### Request interceptors\n\nRun against the raw request **draft** before it is finalized (before JSON serialization and header merging). Mutate the URL, body, or headers:\n\n```typescript\nconst id = api.interceptors.request.use((draft) =\u003e ({\n  ...draft,\n  url: `${draft.url}?trace=1`,\n  headers: { 'x-trace-id': crypto.randomUUID() },\n}));\n\napi.interceptors.request.eject(id); // remove a single interceptor\napi.interceptors.request.clear();   // remove all\n```\n\n### Response interceptors\n\nRun against the full response, in registration order:\n\n```typescript\napi.interceptors.response.use((res) =\u003e {\n  console.log(`${res.request.method} ${res.request.url} -\u003e ${res.status}`);\n  return res;\n});\n```\n\n### Recovering from errors\n\nA response interceptor's second argument handles errors. Return a response to recover, or throw to propagate:\n\n```typescript\napi.interceptors.response.use(undefined, (error) =\u003e {\n  if (error.status === 401) {\n    return refreshAndRetry(error.request); // must return a response-shaped object\n  }\n  throw error;\n});\n```\n\n## Errors\n\nAny non-2xx status, network failure, or unreadable body is thrown as an `ApiError`:\n\n```typescript\nimport { ApiError } from '@panoscool/fetch-client';\n\ntry {\n  await api.get('/missing');\n} catch (error) {\n  if (error instanceof ApiError) {\n    error.status;   // HTTP status, or 0 for network/abort failures\n    error.data;     // parsed error payload, when present\n    error.request;  // the finalized request config\n    error.response; // the raw Response (body still readable)\n    error.cause;    // the original thrown error\n  }\n}\n```\n\n`ApiError` extracts a useful `message` from common payload shapes (`{ detail }`, `{ message }`, `{ error }`, `{ errors: [{ message }] }`, plain text). Aborted requests report `\"Request aborted\"` with `status: 0`.\n\n`error.toJSON()` returns a log-safe view with sensitive request headers (`Authorization`, `Cookie`, `Set-Cookie`, `Proxy-Authorization`, `X-Api-Key`) redacted.\n\n## Cancellation\n\nPass an `AbortSignal` like any other `fetch` call:\n\n```typescript\nconst controller = new AbortController();\nconst promise = api.get('/slow', { signal: controller.signal });\ncontroller.abort();\n// rejects with an ApiError: \"Request aborted\"\n```\n\n## Custom transport\n\n`createFetchTransport` lets you inject a `fetch` implementation — useful in tests or to wrap fetch:\n\n```typescript\nimport { createApiClient, createFetchTransport } from '@panoscool/fetch-client';\n\nconst api = createApiClient({\n  transport: createFetchTransport(myFetch),\n});\n```\n\n## Development\n\n```bash\nbun install\nbun run lint    # biome\nbun test        # bun test runner\nbun run build   # ESM + CJS + type declarations into dist/\n```\n\n## License\n\nMIT — see [LICENSE](LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpanoscool%2Ffetch-client","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpanoscool%2Ffetch-client","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpanoscool%2Ffetch-client/lists"}