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

@zakkudo/fetch

v1.0.1

Published

Make working with native fetch enjoyable.

Readme

@zakkudo/fetch

Make using native fetch enjoyable.

Build Status Coverage Status Known Vulnerabilities Node License

Why use this?

  • Consistancy with simplicity
  • Automatically parses JSON payloads when the content type of the response is application/json
  • Automatically serializes json in the request body
  • Network errors throw an HttpError exception with the exception information for handling
  • Interpolates params into url templates. /users/:id/detail + {params: {id: "joe"}} = /users/joe/detail
  • Complex params are automatically JSON serialized similar to @zakkudo/query-string
  • Proper transformRequest/transformResponse/transformError hooks

Install

# Install using npm
npm install @zakkudo/fetch
# Install using yarn
yarn add @zakkudo/fetch

Examples

Post to an endpoint

import fetch from '@zakkudo/fetch';

//Create a user
fetch('http://example.com/users', {
    method: 'POST'
    body: {
        first_name: 'joe',
        last_name: 'johnson',
    },
}).then((reponse) => {
    console.log(response); // {'id': '1234'}
}.catch((reason) => {
    if (reason.status === 401) {
        return authenticate();
    }

    console.error(reason);
    throw reason;
});

Get data from an endpoint

import fetch from '@zakkudo/fetch';

//Fetch the created user
fetch('http://example.com/users/:id', {
    params: {
        id: '1234'
    },
}).then((reponse) => {
    console.log(response); // {id: '1234', first_name: 'joe', last_name: 'johnson'}
}.catch((reason) => {
    if (reason.status === 401) {
        return authenticate();
    }

    console.error(reason);
    throw reason;
});

Transform everything everywhere

import fetch from '@zakkudo/fetch';

//Fetch the created user
fetch('http://example.com/users/:id', {
    transformRequest(options) {
        return encodeWithJWT(options);
    },
    transformResponse(response) {
        const {first_name, last_name} = response;

        response.full_name = `${first_name} ${last_name}`;

        return response;
    },
    transformError(reason) {
        if (reason.status === 401) {
            window.href = '/login';
        }

        return reason;
    },
    params: {
        id: '1234'
    },
}).then((reponse) => {
    console.log(response); // {id: '1234', first_name: 'joe', last_name: 'johnson', full_name': 'joe johnson'}
});

Handling errors

import fetch from '@zakkudo/fetch';
import HttpError from '@zakkudo/fetch/HttpError';

fetch('http://example.com/does-not-exist').catch((reason) => {
    if (reason instanceof HttpError) {
        console.log(reason.status); // 404
    }
});

Use with async/await

import fetch from '@zakkudo/fetch';
import HttpError from '@zakkudo/fetch/HttpError';

async function get() {
    try {
        const response = await fetch('http://example.com/does-not-exist');
        console.log(response);
    } catch (e) {
        if (e instanceof HttpError) {
            console.log(e.status); // 404
        }
    }
}

API

@zakkudo/fetch~fetch(url, [options]) ⇒ Promise

Kind: Exported function

Returns: Promise - Resolves to the response of the network transaction or rejects with an HttpError
Throws:

  • HttpError For errors during the network transaction
  • UrlError For incorrectly formatted urls
  • QueryStringError On issues during serialization or construction of the query string

| Param | Type | Description | | --- | --- | --- | | url | String | The request url | | [options] | Options | Options modifying the network call, mostly analogous to fetch |

fetch~Options : Object

Options modifying the network call, mostly analogous to fetch

Kind: inner typedef of fetch
Properties

| Name | Type | Default | Description | | --- | --- | --- | --- | | [options.method] | String | 'GET' | GET, POST, PUT, DELETE, etc. | | [options.mode] | String | 'same-origin' | no-cors, cors, same-origin | | [options.cache] | String | 'default' | default, no-cache, reload, force-cache, only-if-cached | | [options.credentials] | String | 'omit' | include, same-origin, omit | | [options.headers] | String | | "application/json; charset=utf-8". | | [options.redirect] | String | 'follow' | manual, follow, error | | [options.referrer] | String | 'client' | no-referrer, client | | [options.body] | String | Object | | JSON.stringify is automatically run for non-string types | | [options.params] | String | Object | | Query params to be appended to the url. The url must not already have params. The serialization uses the same rules as used by @zakkudo/query-string | | [options.transformRequest] | function | Array.<function()> | | Transforms for the request body. When not supplied, it by default json serializes the contents if not a simple string. Also accepts promises as return values for asynchronous work. | | [options.unsafe] | Boolean | | Disable escaping of params in the url | | [options.transformResponse] | function | Array.<function()> | | Transform the response. Also accepts promises as return values for asynchronous work. | | [options.transformError] | function | Array.<function()> | | Transform the error response. Return the error to keep the error state. Return a non Error to recover from the error in the promise chain. A good place to place a login handler when recieving a 401 from a backend endpoint or redirect to another page. It's preferable to never throw an error here which will break the error transform chain in a non-graceful way. Also accepts promises as return values for asynchronous work. |

@zakkudo/fetch/HttpError~HttpError ⇐ Error

An error representing an HTTP error during a network connection.

Kind: Exported class

Extends: Error

new HttpError(status, statusText, [url], [headers], [response])

| Param | Type | Description | | --- | --- | --- | | status | Integer | The http error code | | statusText | String | The string representation of the error | | [url] | String | The url that failed | | [headers] | Object | The headers when the request failed | | [response] | * | The response of the transaction. Determined arbitraility by the server. Can be deserialized json. |

httpError.status

The http error code

Kind: instance property of HttpError

httpError.statusText

The string representation of the error

Kind: instance property of HttpError

httpError.url

The url that failed

Kind: instance property of HttpError

httpError.headers

The headers when the request failed

Kind: instance property of HttpError

httpError.response

The response of the transaction. Determined arbitraility by the server. Can be deserialized json.

Kind: instance property of HttpError

@zakkudo/fetch/UrlError~UrlError ⏏

Aliased error from package @zakkudo/url/UrlError

Kind: Exported class

@zakkudo/fetch/QueryStringError~QueryStringError ⏏

Aliased error from package @zakkudo/url/QueryStringError

Kind: Exported class