A fast, flexible, and fully type-safe HTTP client wrapper around the native fetch API, built for TypeScript and Bun.
- Type-Safe: Built with TypeScript, providing strict typings for requests, responses, and errors.
- Native Fetch: Built entirely on the modern, native
fetchAPI. No bloated dependencies. - No
try/catchHell: Returns standardized success and error objects, allowing for cleaner error handling. - Interceptors: Easily hook into requests and responses globally to add auth tokens, logging, or transform data.
- Timeouts: Native support for aborting requests using timeouts via
AbortController. - Response Parsing: Built-in automatic parsing for
Json,Text,Blob, andArrayBuffer. - Query Parameters: Easily pass
paramsobjects which are automatically serialized into URL query strings. - Configurable Client: Create multiple client instances with base URLs and global configs.
- Lightweight: Minimal overhead.
To install boltfetch in your project:
bun install bolt-fetch-tsOr using npm/pnpm/yarn:
npm install bolt-fetch-ts
pnpm install bolt-fetch-ts
yarn add bolt-fetch-ts(Note: While optimized for Bun, it can also be used in any Node.js, Deno, or browser environments that support native fetch and ES modules.)
BoltFetch avoids throwing errors for HTTP failures or network issues. Instead, it always returns a standard object. This means you can say goodbye to nested try/catch blocks and handle errors gracefully.
const response = await boltfetch.get("/api/data");
if (!response.success) {
// Handle error (response is BoltFetchError)
console.error(response.status, response.message);
return;
}
// Handle success (response is BoltFetchResponse)
console.log(response.data);You can use the default instance of boltfetch directly for simple requests.
import { boltfetch } from "boltfetch";
async function fetchUser() {
const response = await boltfetch.get<{ id: number; name: string }>(
"https://api.github.com/users/himanshupadecha"
);
if (response.success) {
console.log("User Data:", response.data.name);
} else {
console.error("Error:", response.message);
}
}
fetchUser();BoltFetch supports all standard HTTP methods.
const response = await boltfetch.get<User[]>("/users", {
params: { role: "admin", active: true }, // Appends ?role=admin&active=true
});Data passed to the second argument is automatically serialized to JSON.
const newPost = { title: "Hello", content: "World" };
const response = await boltfetch.post<Post>("/posts", newPost);const updatedPost = { title: "Hello Updated", content: "World Updated" };
const response = await boltfetch.put<Post>("/posts/1", updatedPost);const partialUpdate = { title: "Hello Patched" };
const response = await boltfetch.patch<Post>("/posts/1", partialUpdate);const response = await boltfetch.delete<{ deletedId: number }>("/posts/1");Every request method accepts a configuration object as its last argument.
const response = await boltfetch.get("/data", {
timeout: 5000, // Aborts request after 5 seconds
headers: {
"Authorization": "Bearer token",
"Custom-Header": "custom-value"
},
params: {
search: "query",
limit: 10
},
responseType: "Json" // Options: "Json" | "Text" | "Blob" | "ArrayBuffer"
});For more complex applications, you can create a configured instance with a base URL, global configurations, and interceptors.
import { configureBoltFetchClient } from "boltfetch";
const apiClient = configureBoltFetchClient({
baseUrl: "https://api.example.com/v1",
globalConfig: {
timeout: 10000, // Global 10s timeout
headers: { "X-App-Version": "1.0.0" }
},
// Request Interceptor: Modify config before the request is sent
requestInterceptor: (config) => {
const token = localStorage.getItem("token");
if (token) {
config.headers = {
...config.headers,
Authorization: `Bearer ${token}`,
};
}
return config;
},
// Response Interceptor: Modify or log the response
responseInterceptor: (response) => {
console.log(`[${response.config.reqType}] ${response.config.url} - ${response.status}`);
return response;
},
});
// Usage
const response = await apiClient.get("/users");Creates and returns a new BoltFetch instance.
config properties:
baseUrl(string): The base URL prepended to all request paths.globalConfig(object): Default configuration for requests (e.g.,timeout,headers,params,responseType).requestInterceptor(function): Hook to modify the request configuration before sending.responseInterceptor(function): Hook to modify or log the response object upon receiving it.
Returned when a request is successful (response.ok is true).
type BoltFetchResponse<T = any> = {
status: number;
success: true; // Always true for successful requests
data: T; // The parsed response data
statusText: "OK" | "NOT FOUND";
headers: Record<string, string>;
config: Record<string, string>;
};Returned when a request fails (network error, timeout, or !response.ok).
type BoltFetchError = {
status: number;
message: string;
success: false; // Always false for errors
url: string;
method: string;
moreInfo: any; // Response payload from the server, if any
};type globalRequestConfig = {
timeout?: number;
headers?: Record<string, string>;
params?: Record<string, string | number | boolean | null | undefined>;
responseType?: "Json" | "Text" | "Blob" | "ArrayBuffer";
};Contributions, issues, and feature requests are welcome! Feel free to check out the issues page.
This project is MIT licensed.