npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@gladknee/fetchy

v2.2.0

Published

A zero dependency wrapper for fetch that provides type-safe returns and custom error handling

Readme

fetchy

Fetchy is an open source, zero dependency wrapper for JavaScript's fetch function. It provides the following benefits:

  1. Simple get, post, put and delete functions
  2. Accepts TypeScript generics for type-safe returns.
  3. Returns errors rather than throwing them, removing the need to use try/catch blocks. (version ≥2.0.0)
  4. Easily detects and handles different types of fetch errors.

Documentation

Quick Start

  1. Install the package.

    npm i @gladknee/fetchy

  2. Import the default export from the library.

    import fetchy from "@gladknee/fetchy"

  3. The imported object provides four functions for making requests: get, post, put, delete.

import fetchy from "@gladknee/fetchy"

async function yourFunction() {
  const [data, error, response] = await fetchy.get(
    "https://server.com/api/endpoint"
  )

  if (data) {
    // handle returned data
  } else {
    // handle error
  }
}

// You can also pass config options like a normal fetch call...

const [data, error] = await fetchy.get("https://server.com/api/endpoint", {
  headers: { Authorization: "Bearer XXXXXX" },
})

NOTE: For versions <2.0.0, the function returns an object with a data key. If an error occurs, the error is thrown.

HTTP Methods

function get<T = unknown>(
  url: string,
  options?: Omit<RequestInit, "method">
): Promise<FetchyResponse<T>> {}

function post<T = unknown>(
  url: string,
  options?: Omit<RequestInit, "method">
): Promise<FetchyResponse<T>> {}

function put<T = unknown>(
  url: string,
  options?: Omit<RequestInit, "method">
): Promise<FetchyResponse<T>> {}

function delete<T = unknown>(
  url: string,
  options?: Omit<RequestInit, "method">
): Promise<FetchyResponse<T>> {}

Types

type FetchyResponse<T> =
  | [data: T, error: undefined, response: Response]
  | [data: undefined, error: FetchyError, response: Response]

export type FetchyError = Error | ({ status: number } & Record<string, any>)

Error Handling

The imported fetchy object also contains a handleError method. You can call this function by passing two required parameters: the error and your error handling callback configuration.

NOTE: If you are using versions <2.0.0, you will need to import handleError separately from the fetchy default export. You will also need to call the function inside your catch block.

function handleError(e: FetchyError, callbacks: CallbackConfig)

type CallbackConfig = {
  status?: {
    [key: number]: (e?: FetchyError) => void
    other?: (e?: FetchyError) => void
    all?: (e?: FetchyError) => void
  }
  body?: {
    [key: string]: (value?: any, e?: FetchyError) => void
  }
  client?: {
    fetch?: (e?: FetchyError) => void
    network?: (e?: FetchyError) => void
    abort?: (e?: FetchyError) => void
    security?: (e?: FetchyError) => void
    syntax?: (e?: FetchyError) => void
    all?: (e?: FetchyError) => void
  }
  other?: (e?: FetchyError) => void
  all?: (e?: FetchyError) => void
}

Handling status codes

async function getAndGreetUser() {
  const [data, error] = await fetchy.get("https://api.com/users/1")

  if (data) {
    greetUser(data)
  } else {
    fetchy.handleError(error, {
      status: {
        401: (error) => {
          /* Do something if 401 response */
        },
        500: (error) => {
          /* Do something if 500 response */
        },
        other: (error) => {
          /* Do something on any other non 200-300 statuses */
        },
        all: (error) => {
          /* Do something on any non 200-300 status */
        },
      },
    })
  }
}

Handling response body

async function getAndGreetUser() {
  const [data, error] = await fetchy.get("https://api.com/users/1")

  if (data) {
    greetUser(data)
  } else {
    fetchy.handleError(error, {
      body: {
        fieldName: (value, error) => {
          switch (value) {
            case "SOME_VALUE":
              // Do something if response includes { fieldName: "SOME_VALUE" }
              break
            case "SOME_OTHER_VALUE":
              // Do something if response includes { fieldName: "SOME_OTHER_VALUE "}
              break
            default:
            // Do something if response includes { fieldName: <anything else> }
          }
        },
      },
    })
  }
}

Handling client-side errors

async function getAndGreetUser() {
  const [data, error] = await fetchy.get("https://api.com/users/1")

  if (data) {
    greetUser(data)
  } else {
    fetchy.handleError(error, {
      client: {
        fetch: (error) => {
          /* Do something if fetch failed */
        },
        network: (error) => {
          /* Do something if network error */
        },
        abort: (error) => {
          /* Do something if user aborted */
        },
        security: (error) => {
          /* Do something if security error */
        },
        syntax: (error) => {
          /* Do something if syntax error */
        },
        all: (error) => {
          /* Do something if any client-side error */
        },
      },
    })
  }
}

Handling any other uncaught errors

async function getAndGreetUser() {
  const [data, error] = await fetchy.get("https://api.com/users/1")

  if (data) {
    greetUser(data)
  } else {
    fetchy.handleError(error, {
      status: {
        401: (error) => {
          /* Do something if 401 response */
        },
      },
      other: (error) => {
        /* Do something if any other error is thrown */
      },
    })
  }
}

Handling all errors

You can also execute a callback on any error. This will be executed along with any other triggered callbacks. So in this example, on a 401 error, the user is redirected and the error is logged.

async function getAndGreetUser() {
  const [data, error] = await fetchy.get("https://api.com/users/1")

  if (data) {
    greetUser(data)
  } else {
    fetchy.handleError(error, {
      status: {
        401: () => redirect("/auth"),
      },
      all: (error) => {
        logError(error)
      },
    })
  }
}

Example: Combined error handling

NOTE: If multiple error handling conditions are triggered, each of their callbacks will be executed.

async function getAndGreetUser() {
  const [data, error] = await fetchy.get("https://api.com/users/1")

  if (data) {
    greetUser(data)
  } else {
    fetchy.handleError(error, {
      status: {
        401: () => redirect("/auth"),
      },
      body: {
        errorMessage: (value, error) => {
          switch (value) {
            case "USER_NOT_ACTIVE":
              alert("Your account is no longer active.")
              break
            default:
              alert(`Error: ${value}`)
          }
        },
      },
      client: {
        network: () => alert("There was a network error."),
      },
      all: (error) => logError(error),
    })
  }
}

Helpful tips

As you can see in the previous example, combining multiple types of error handling can lead to bulky code. One helpful tip is to separate out your error handling logic into their own object(s) and pass them in to your handleError callbacks.

Example:

import type { CallbackConfig } from "@gladknee/fetchy"

const handleStatusErrors = {
  401: () => router.push("/auth/signin"),
  402: () => router.push("/upgrade"),
  500: (error: any) => logInternalServerError(eror),
  // ...etc
}

const handleClientErrors = {
  fetch: () => alert("Please check your internet connection."),
  network: () => alert("We experienced a network error. Please try again."),
}

const handleErrorMessages = (message: string) => {
  switch (message) {
    case "USER_NOT_FOUND":
      alert("You do not have an account.")
      break
    case "USER_DEACTIVATED":
      alert("Your account has been deactivated.")
      break
    default:
      alert(`Error: ${message}`)
  }
}

function logError(error: any) {
  // do something to log any errors
}

const myErrorHandlers: CallbackConfig = {
  status: handleStatusErrors,
  client: handleClientErrors,
  body: {
    errorMessage: handleErrorMessages,
  },
  all: logError,
}

async function someRequest() {
  const [data, error] = await fetchy.get("https://api.com/users/1")

  if (data) {
    greetUser(data)
  } else {
    fetchy.handleErrors(error, myErrorHandlers)
  }
}

Use with TanStack Query (react-query)

Fetchy works great with Tanstack Query. Below is a popular implementation.

export async function getUser() {
  const [data, error] = await fetchy.get("https://api.com/users/1")

  if (data) return data
  else throw error // Throw the error so that it bubbles up to your useQuery hook
}

export function SomeComponent() {
  const { data, isError, error } = useQuery({
    queryKey: ["yourkey"],
    queryFn: getUser,
  })

  useEffect(() => {
    if (isError) {
      fetchy.handleError(error, callbackConfig)
    }
  }, [isError, error])
}