A tiny wrapper built around fetch with an intuitive syntax. :candy:
A tiny wrapper built around fetch with an intuitive syntax. :candy:
wretch is a small wrapper around fetch designed to simplify the way to perform network requests and handle responses.# 1️⃣ Install
npm i wretch…Fetch needs a second callback to process the response body.
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(json => {
//Do stuff with the parsed json
});Wretch does it for you.
// Use .res for the raw response, .text for raw text, .json for json, .blob for a blob …
wretch("https://jsonplaceholder.typicode.com/posts/1")
.get()
.json(json => {
// Do stuff with the parsed json
return json
});Fetch won't reject on HTTP error status.
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => {
if(!response.ok) {
if(response.status === 404) throw new Error("Not found")
else if(response.status === 401) throw new Error("Unauthorized")
else if(response.status === 418) throw new Error("I'm a teapot !")
else throw new Error("Other error")
}
else {/* … */}
})
.then(data => {/* … */})
.catch(error => { /* … */ })Wretch throws when the response is not successful and contains helper methods to handle common codes.
wretch("https://jsonplaceholder.typicode.com/posts/1")
.get()
.notFound(error => { /* … */ })
.unauthorized(error => { /* … */ })
.error(418, error => { /* … */ })
.res(response => {/* … */ })
.catch(error => { /* uncaught errors */ })With fetch you have to set the header, the method and the body manually.
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ "hello": "world" })
}).then(response => {/* … */})
// Omitting the data retrieval and error management parts…With wretch, you have shorthands at your disposal.
wretch("https://jsonplaceholder.typicode.com/posts")
.post({ "hello": "world" })
.res(response => { /* … */ })A Wretch object is immutable which means that you can reuse previous instances safely.
…npm i wretch # or yarn/pnpm add wretchThe package contains multiple bundles depending on the format and feature set located under the /dist/bundle folder.
If you pick the core bundle, then to plug addons you must import them separately from
/dist/bundle/addons/[addonName].min.js
| Feature set | File Name |
|---|---|
| Core features only | wretch.min.js |
| Core + all addons | wretch.all.min.js |
| Format | Extension |
|---|---|
| ESM | .min.mjs |
| CommonJS | .min.cjs |
| UMD | .min.js |
<script src="https://unpkg.com/wretch"></script>
<script type="module">
import wretch from 'https://cdn.skypack.dev/wretch/dist/bundle/wretch.all.min.mjs'
// … //
</script>wretch@^3 is compatible with modern browsers only. For older browsers please use wretch@^1.
Wretch is compatible with and tested in Node.js >= 22.
For older Node.js versions, please use wretch@^2.
Node.js 22+ includes native fetch support and all required Web APIs (FormData, URLSearchParams, AbortController, etc.) out of the box, so no polyfills are needed.
Works with Deno out of the box.
deno add npm:wretchimport wretch from "wretch";
const text = await wretch("https://httpbingo.org").get("/status/200").text();
console.log(text); // -> { "code": 200, "description": "OK" }Works with Bun out of the box.
bun add wretchimport wretch from "wretch";
const text = await wretch("https://httpbingo.org").get("/status/200").text();
console.log(text); // -> { "code": 200, "description": "OK" }// ECMAScript modules
import wretch from "wretch"
// CommonJS
const wretch = require("wretch")
// Global variable (script tag)
window.wretch// REST API Client
const api = wretch("https://jsonplaceholder.typicode.com")
.auth("Bearer token")
.resolve(r => r.json())
const users = await api.get("/users")
const user = await api.post({ name: "John" }, "/users")
users// File Upload with Progress
import ProgressAddon from "wretch/addons/progress"
import FormDataAddon from "wretch/addons/formData"
await wretch("https://httpbingo.org/post")
.addon([FormDataAddon, ProgressAddon()])
.formData({ file: file })
.post()
.progress((loaded, total) => console.log(`${(loaded/total*100).toFixed()}%`))
.json()// Auto-retry on Network Failure
import { retry } from "wretch/middlewares"
const resilientApi = wretch()
.middlewares([retry({ maxAttempts: 3, retryOnNetworkError: true })])// Type-safe TypeScript
interface User { id: number; name: string; email: string }
const user = await wretch("https://jsonplaceholder.typicode.com")
.get("/users/1")
.json<User>() // Fully typed!
user// Automatic Token Refresh
const api = wretch("https://httpbingo.org/basic-auth/user/pass")
.addon(BasicAuthAddon)
.resolve(w => w.unauthorized(async (error, req) => {
const newToken = await refreshToken()
return req
.basicAuth("user", "pass")
.unauthorized(e => {
console.log("Still unauthorized after token refresh");
throw e
})
.fetch()
.json()
}))You can provide a custom fetch implementation using the .fetchPolyfill() method. This is useful for for a variety of use cases including mocking, adding logging, timing, or other custom behavior to all requests made through a wretch instance.
import wretch from "wretch"
// Per-instance custom fetch
const api = wretch("https://jsonplaceholder.typicode.com")
.fetchPolyfill((url, opts) => {
console.log('Fetching:', url)
console.time(url)
return fetch(url, opts).finally(() => {
console.timeEnd(url)
})
})
await api.get("/posts").json()Converts a wretch instance into a fetch-like function, preserving all configuration (middlewares, catchers, headers, etc.). Useful for integrating wretch with libraries that expect a fetch signature.
const myFetch = wretch("https://jsonplaceholder.typicode.com")
.auth("Bearer token")
.catcher(401, (err) => console.log("Unauthorized"))
.toFetch()
// Use like regular fetch
const response = await myFetch("/users", { method: "GET" })
response// Pass to libraries expecting fetch
import { createClient } from "@apollo/client"
const client = createClient({
fetch: wretch().auth("Bearer token").toFetch()
})A high level overview of the successive steps that can be chained to perform a request and parse the result.
…Step-by-step breakdown:
// First, instantiate wretch
wretch(baseUrl, baseOptions)The "request" chain starts here.
// Optional - A set of helper methods to set the default options, set accept header, change the current url…
.<helper method(s)>()
// Optional - Serialize an object to json or FormData formats and sets the body & header field if needed
.<body type>()
// Required - Sends the get/put/post/delete/patch request.
.<http method>()The "response" chain starts here.
Fetch is called after the request chain ends and before the response chain starts.
The request is on the fly and now it is time to chain catchers and finally call a response type handler.
// Optional - You can chain error handlers here
.<catcher(s)>()
// Required - Specify the data type you need, which will be parsed and handed to you
.<response type>()
// >> Ends the response chain.From this point on, wretch returns a standard Promise.
.then(…)
.catch(…)Here's how the chaining works in practice:
await wretch("https://api.example.com") // Base URL
.headers({ "X-Api-Key": "secret" }) // Helper method
.query({ limit: 10 }) // Helper method
.json({ name: "Alice", role: "admin" }) // Body type
.post("/users") // HTTP method (starts request)
.badRequest(err => console.log("Invalid")) // Catcher
.unauthorized(err => console.log("No auth")) // Catcher
.json(user => console.log(user)) // Response typeLooking for common patterns and solutions? Check out the Recipes Guide for practical examples covering:
No open issues yet, or sync has not completed.