Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
W

wretch

> 数据库
Open source

A tiny wrapper built around fetch with an intuitive syntax. :candy:

5.2K stars0 likes2 views
WebsiteGitHub

About

A tiny wrapper built around fetch with an intuitive syntax. :candy:



Wretch

A tiny (~1.8KB g-zipped) wrapper built around fetch with an intuitive syntax.

f[ETCH] [WR]apper
Wretch 3.0 is now live ! Check out the Migration Guide for upgrading from v2, and please have a look at the releases and the changelog after each update for new features and breaking changes.
And if you like the library please consider becoming a sponsor ❤️.

Features

wretch is a small wrapper around fetch designed to simplify the way to perform network requests and handle responses.

  • Small - core is less than 1.8KB g-zipped
  • Intuitive - lean API, handles errors, headers and (de)serialization
  • Immutable - every call creates a cloned instance that can then be reused safely
  • Modular - plug addons to add new features, and middlewares to intercept requests
  • Isomorphic - compatible with modern browsers, Node.js 22+, Deno and Bun
  • Type safe - strongly typed, written in TypeScript
  • ✅ Proven - fully covered by unit tests and widely used
  • Maintained - alive and well for many years

Table of Contents

  • Quick Start
  • Motivation
  • Installation
  • Compatibility
  • Usage
  • Recipes
  • Api
  • Addons
  • Middlewares
  • Migration Guides
  • License

Quick Start

bash
# 1️⃣ Install
npm i wretch
…

Motivation

Because having to write a second callback to process a response body feels awkward.

Fetch needs a second callback to process the response body.

javascript
fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => response.json())
  .then(json => {
    //Do stuff with the parsed json
  });

Wretch does it for you.

javascript
// 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
  });

Because manually checking and throwing every request error code is tedious.

Fetch won't reject on HTTP error status.

javascript
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.

javascript
wretch("https://jsonplaceholder.typicode.com/posts/1")
  .get()
  .notFound(error => { /* … */ })
  .unauthorized(error => { /* … */ })
  .error(418, error => { /* … */ })
  .res(response => {/* … */ })
  .catch(error => { /* uncaught errors */ })

Because sending a json object should be easy.

With fetch you have to set the header, the method and the body manually.

javascript
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.

javascript
wretch("https://jsonplaceholder.typicode.com/posts")
  .post({ "hello": "world" })
  .res(response => { /* … */ })

Because configuration should not rhyme with repetition.

A Wretch object is immutable which means that you can reuse previous instances safely.

…

Installation

Package Manager

bash
npm i wretch # or yarn/pnpm add wretch

<script> tag

The package contains multiple bundles depending on the format and feature set located under the /dist/bundle folder.

Bundle variants

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
xml

<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>

Compatibility

Browsers

wretch@^3 is compatible with modern browsers only. For older browsers please use wretch@^1.

Node.js

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.

Deno

Works with Deno out of the box.

bash
deno add npm:wretch
typescript
import wretch from "wretch";

const text = await wretch("https://httpbingo.org").get("/status/200").text();
console.log(text); // -> { "code": 200, "description": "OK" }

Bun

Works with Bun out of the box.

bash
bun add wretch
typescript
import wretch from "wretch";

const text = await wretch("https://httpbingo.org").get("/status/200").text();
console.log(text); // -> { "code": 200, "description": "OK" }

Usage

Import

typescript
// ECMAScript modules
import wretch from "wretch"
// CommonJS
const wretch = require("wretch")
// Global variable (script tag)
window.wretch

Common Use Cases

javascript
//  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
javascript
//  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()
javascript
//  Auto-retry on Network Failure
import { retry } from "wretch/middlewares"

const resilientApi = wretch()
  .middlewares([retry({ maxAttempts: 3, retryOnNetworkError: true })])
typescript
//  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
javascript
//  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()
  }))

Custom Fetch Implementation

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.

javascript
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()

toFetch() - Fetch Adapter

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.

javascript
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
javascript
// Pass to libraries expecting fetch
import { createClient } from "@apollo/client"

const client = createClient({
  fetch: wretch().auth("Bearer token").toFetch()
})

Chaining

A high level overview of the successive steps that can be chained to perform a request and parse the result.

…

Step-by-step breakdown:

typescript
// First, instantiate wretch
wretch(baseUrl, baseOptions)

The "request" chain starts here.

typescript
  // 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.

typescript
  // 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.

typescript
  .then(…)
  .catch(…)

Concrete Example

Here's how the chaining works in practice:

javascript
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 type

Recipes

Looking for common patterns and solutions? Check out the Recipes Guide for practical examples covering:

  • Error Handling - Parsing error response bodies, custom error types, global handlers
  • TypeScript Patterns - Typing precomposed instances, reusable catchers
  • File Uploads - Progress tracking, FormData handling
  • Query Strings - Filtering undefined values
  • Request Control - Combining timeouts with AbortControllers, aborting on errors
  • Advanced Patterns - Token refresh & replay, schema validation, async polling

[API ](http

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptajaxfetchformdatahttp

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库