@richardtwi-dbg/fetchly
v0.5.3
Published
A lightweight, fully typed fetch client
Maintainers
Readme
Fetchly
Fetchly is a lightweight, type-safe HTTP client built on top of the native Fetch API.
It removes repetitive response handling while keeping the API close to fetch.
It shares nothing but the name with the similar npm package fetchly.
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error();
}
const users = await response.json();With Fetchly:
const users = await api.get<User[]>("/users");Status
Fetchly is currently under active development.
Features
- Type-safe request results
GET,POST,PUT,PATCH, andDELETEmethods- Configurable base URL
- Client-level and request-level headers
- Query parameters
- Automatic JSON serialization and JSON response parsing
- Typed API errors
- Request timeout and cancellation through
AbortSignal - Request and response interceptors
- Middleware and plugin API
- Retry support for temporary server errors
- JWT access-token refresh plugin
- FormData plugin
- File download helpers
- ESM, CommonJS, and TypeScript declarations
Installation
npm install @richardtwi-dbg/fetchlyBasic usage
import { createClient } from "fetchly";
interface User {
id: number;
name: string;
}
const api = createClient({
baseUrl: "/api",
});
const users = await api.get<User[]>("/users");
const user = await api.get<User>("/users/1");Plugins
Fetchly uses middleware-based plugins for functionality that needs to control a request flow, such as retries, authentication, uploads, and caching.
Plugins can be installed after client creation:
const api = createClient();
api.use(plugin);Or during creation:
const api = createClient({
plugins: [pluginA, pluginB],
});Retry
Retry temporary server failures:
const api = createClient({
retry: {
count: 3,
delay: 1_000,
},
});By default, Fetchly retries responses with statuses 500, 502, 503, and 504.
You can customize retry statuses:
const api = createClient({
retry: {
count: 2,
delay: 500,
statuses: [429, 500, 503],
},
});The same option can be applied to a single request:
await api.get<User[]>("/users", {
retry: {
count: 2,
delay: 250,
},
});JWT token refresh
Use the JWT plugin to add an access token and refresh it after a 401 response.
import { createClient, jwt } from "@richardtwi-dbg/fetchly";
let accessToken = "initial-token";
const api = createClient({
baseUrl: "/api",
});
api.use(jwt({
getAccessToken: () => accessToken,
async refreshToken() {
const response = await fetch("/api/auth/refresh", {
method: "POST",
credentials: "include",
});
if (!response.ok) {
throw new Error("Unable to refresh access token");
}
const data = await response.json();
accessToken = data.accessToken;
},
}));When multiple requests receive 401 simultaneously, Fetchly runs one refresh operation and waits for it before retrying the failed requests.
A request is refreshed only once. If the repeated request also returns 401, Fetchly throws ApiError.
FormData
Use the formData plugin to convert an object body into FormData.
import { createClient, formData } from "@richardtwi-dbg/fetchly";
const api = createClient();
api.use(formData());
await api.post("/users/avatar", {
body: {
name: "Richard",
tags: ["typescript", "fetch"],
profile: {
active: true,
},
},
});The example above sends these fields:
name = Richard
tags[0] = typescript
tags[1] = fetch
profile[active] = trueFetchly does not set Content-Type manually for FormData. The browser adds the required multipart/form-data boundary automatically.
Download files
Download helpers return a Blob, response content type, and a filename when the server sends Content-Disposition.
const file = await api.download("/reports/monthly");
console.log(file.filename);
console.log(file.contentType);
console.log(file.blob);Save a downloaded file in the browser:
const file = await api.download("/reports/monthly");
const url = URL.createObjectURL(file.blob);
const link = document.createElement("a");
link.href = url;
link.download = file.filename ?? "download";
link.click();
URL.revokeObjectURL(url);Client configuration
const api = createClient({
baseUrl: "/api",
headers: {
Authorization: "Bearer token",
},
timeout: 10000,
});Configuration options:
| Option | Type | Description |
|---|---|---|
| baseUrl | string | Prefix added to every request path |
| headers | HeadersInit | Headers sent with every request |
| timeout | number | Default timeout in milliseconds |
Query parameters
const users = await api.get<User[]>("/users", {
query: {
page: 1,
size: 50,
active: true,
},
});The resulting request URL:
/api/users?page=1&size=50&active=trueValues equal to null or undefined are omitted.
JSON request body
const user = await api.post<User>("/users", {
body: {
name: "John",
},
});Fetchly automatically:
- serializes the body with
JSON.stringify - sets
Content-Type: application/json - sets
Accept: application/json
You can override default headers for an individual request:
const user = await api.post<User>("/users", {
headers: {
Authorization: "Bearer another-token",
},
body: {
name: "John",
},
});Request headers take precedence over client headers.
HTTP methods
api.get<User[]>("/users");
api.post<User>("/users", {
body: { name: "John" },
});
api.put<User>("/users/1", {
body: { name: "John Doe" },
});
api.patch<User>("/users/1", {
body: { name: "Jane Doe" },
});
api.delete<void>("/users/1");Errors
Fetchly throws ApiError when the server responds with a non-success HTTP status.
import { ApiError } from "fetchly";
try {
await api.get<User>("/users/1");
} catch (error) {
if (error instanceof ApiError) {
console.log(error.status);
console.log(error.body);
console.log(error.headers);
}
}ApiError contains:
| Property | Description |
|---|---|
| status | HTTP response status |
| body | Parsed JSON body or response text |
| headers | Response headers |
Timeout
Set a timeout for the whole client:
const api = createClient({
baseUrl: "/api",
timeout: 5000,
});Or override it for one request:
await api.get<User[]>("/users", {
timeout: 2000,
});A timed-out request throws TimeoutError.
import { TimeoutError } from "fetchly";
try {
await api.get<User[]>("/slow-endpoint");
} catch (error) {
if (error instanceof TimeoutError) {
console.log(error.timeout);
}
}Cancellation
Use a native AbortController to cancel a request.
const controller = new AbortController();
const request = api.get<User[]>("/users", {
signal: controller.signal,
});
controller.abort();
await request;Development
Install dependencies:
npm installRun type checks:
npm run typecheckRun tests:
npm testBuild the package:
npm run buildRoadmap
- [x] Request and response interceptors.
- [x] Retry support for temporary server errors
- [x] JWT token refresh
- [x] FormData upload support
- [x] File download helpers
- [x] Middleware API
- [ ] Cache support and TTL
- [ ] React hooks package
- [ ] OpenAPI client generation
- [ ] GitHub Actions CI
- [x] npm publishing and release automation
License
MIT
