• Stars
    star
    5,637
  • Rank 7,242 (Top 0.2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 8 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ• Bare minimum 500b fetch polyfill.

unfetch
npm gzip size downloads travis

unfetch

Tiny 500b fetch "barely-polyfill"

  • Tiny: about 500 bytes of ES3 gzipped
  • Minimal: just fetch() with headers and text/json responses
  • Familiar: a subset of the full API
  • Supported: supports IE8+ (assuming Promise is polyfilled of course!)
  • Standalone: one function, no dependencies
  • Modern: written in ES2015, transpiled to 500b of old-school JS

πŸ€” What's Missing?

  • Uses simple Arrays instead of Iterables, since Arrays are iterables
  • No streaming, just Promisifies existing XMLHttpRequest response bodies
  • Use in Node.JS is handled by isomorphic-unfetch


Installation

For use with node and npm:

npm i unfetch

Otherwise, grab it from unpkg.com/unfetch.


Usage: As a Polyfill

This automatically "installs" unfetch as window.fetch() if it detects Fetch isn't supported:

import 'unfetch/polyfill'

// fetch is now available globally!
fetch('/foo.json')
  .then( r => r.json() )
  .then( data => console.log(data) )

This polyfill version is particularly useful for hotlinking from unpkg:

<script src="https://unpkg.com/unfetch/polyfill"></script>
<script>
  // now our page can use fetch!
  fetch('/foo')
</script>

Usage: As a Ponyfill

With a module bundler like rollup or webpack, you can import unfetch to use in your code without modifying any globals:

// using JS Modules:
import fetch from 'unfetch'

// or using CommonJS:
const fetch = require('unfetch')

// usage:
fetch('/foo.json')
  .then( r => r.json() )
  .then( data => console.log(data) )

The above will always return unfetch(). (even if window.fetch exists!)

There's also a UMD bundle available as unfetch/dist/unfetch.umd.js, which doesn't automatically install itself as window.fetch.


Examples & Demos

Real Example on JSFiddle ➑️

// simple GET request:
fetch('/foo')
  .then( r => r.text() )
  .then( txt => console.log(txt) )


// complex POST request with JSON, headers:
fetch('/bear', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ hungry: true })
}).then( r => {
  open(r.headers.get('location'));
  return r.json();
})

API

While one of Unfetch's goals is to provide a familiar interface, its API may differ from other fetch polyfills/ponyfills. One of the key differences is that Unfetch focuses on implementing the fetch() API, while offering minimal (yet functional) support to the other sections of the Fetch spec, like the Headers class or the Response class. Unfetch's API is organized as follows:

fetch(url: string, options: Object)

This function is the heart of Unfetch. It will fetch resources from url according to the given options, returning a Promise that will eventually resolve to the response.

Unfetch will account for the following properties in options:

  • method: Indicates the request method to be performed on the target resource (The most common ones being GET, POST, PUT, PATCH, HEAD, OPTIONS or DELETE).
  • headers: An Object containing additional information to be sent with the request, e.g. { 'Content-Type': 'application/json' } to indicate a JSON-typed request body.
  • credentials: ⚠ Accepts a "include" string, which will allow both CORS and same origin requests to work with cookies. As pointed in the 'Caveats' section, Unfetch won't send or receive cookies otherwise. The "same-origin" value is not supported. ⚠
  • body: The content to be transmitted in request's body. Common content types include FormData, JSON, Blob, ArrayBuffer or plain text.

response Methods and Attributes

These methods are used to handle the response accordingly in your Promise chain. Instead of implementing full spec-compliant Response Class functionality, Unfetch provides the following methods and attributes:

response.ok

Returns true if the request received a status in the OK range (200-299).

response.status

Contains the status code of the response, e.g. 404 for a not found resource, 200 for a success.

response.statusText

A message related to the status attribute, e.g. OK for a status 200.

response.clone()

Will return another Object with the same shape and content as response.

response.text(), response.json(), response.blob()

Will return the response content as plain text, JSON and Blob, respectively.

response.headers

Again, Unfetch doesn't implement a full spec-compliant Headers Class, emulating some of the Map-like functionality through its own functions:

  • headers.keys: Returns an Array containing the key for every header in the response.
  • headers.entries: Returns an Array containing the [key, value] pairs for every Header in the response.
  • headers.get(key): Returns the value associated with the given key.
  • headers.has(key): Returns a boolean asserting the existence of a value for the given key among the response headers.

Caveats

Adapted from the GitHub fetch polyfill readme.

The fetch specification differs from jQuery.ajax() in mainly two ways that bear keeping in mind:

  • By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session.
fetch('/users', {
  credentials: 'include'
});
  • The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally, and it will only reject on network failure or if anything prevented the request from completing.

    To have fetch Promise reject on HTTP error statuses, i.e. on any non-2xx status, define a custom response handler:

fetch('/users')
  .then(response => {
    if (response.ok) {
      return response;
    }
    // convert non-2xx HTTP responses into errors:
    const error = new Error(response.statusText);
    error.response = response;
    return Promise.reject(error);
  })
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

Contribute

First off, thanks for taking the time to contribute! Now, take a moment to be sure your contributions make sense to everyone else.

Reporting Issues

Found a problem? Want a new feature? First of all see if your issue or idea has already been reported. If it hasn't, just open a new clear and descriptive issue.

Submitting pull requests

Pull requests are the greatest contributions, so be sure they are focused in scope, and do avoid unrelated commits.

πŸ’ Remember: size is the #1 priority.

Every byte counts! PR's can't be merged if they increase the output size much.

  • Fork it!
  • Clone your fork: git clone https://github.com/<your-username>/unfetch
  • Navigate to the newly cloned directory: cd unfetch
  • Create a new branch for the new feature: git checkout -b my-new-feature
  • Install the tools necessary for development: npm install
  • Make your changes.
  • npm run build to verify your change doesn't increase output size.
  • npm test to make sure your change doesn't break anything.
  • Commit your changes: git commit -am 'Add some feature'
  • Push to the branch: git push origin my-new-feature
  • Submit a pull request with full remarks documenting your changes.

License

MIT License Β© Jason Miller

More Repositories

1

mitt

πŸ₯Š Tiny 200 byte functional event emitter / pubsub.
TypeScript
9,030
star
2

htm

Hyperscript Tagged Markup: JSX alternative using standard tagged templates, with compiler support.
JavaScript
8,661
star
3

microbundle

πŸ“¦ Zero-configuration bundler for tiny modules.
JavaScript
8,055
star
4

greenlet

🦎 Move an async function into its own thread.
JavaScript
4,621
star
5

workerize

πŸ—οΈ Run a module in a Web Worker.
JavaScript
4,287
star
6

redaxios

The Axios API, as an 800 byte Fetch wrapper.
JavaScript
4,131
star
7

unistore

🌢 350b / 650b state container with component actions for Preact & React
JavaScript
2,865
star
8

express-es6-rest-api

πŸ”‹ Starter project for an ES6 RESTful Express API.
JavaScript
2,460
star
9

workerize-loader

πŸ—οΈ Automatically move a module into a Web Worker (Webpack loader)
JavaScript
2,283
star
10

snarkdown

😼 A snarky 1kb Markdown parser written in JavaScript
JavaScript
2,180
star
11

stockroom

πŸ—ƒ Offload your store management to a worker easily.
JavaScript
1,758
star
12

dlv

Safe deep property access in 120 bytes. x = dlv(obj, 'a.b.x')
JavaScript
1,217
star
13

karmatic

πŸ¦‘ Easy automatic (headless) browser testing with Jest's API, but powered by Karma & Webpack.
JavaScript
1,181
star
14

decko

πŸ’¨ The 3 most useful ES7 decorators: bind, debounce and memoize
JavaScript
1,038
star
15

preact-boilerplate

🎸 Ready-to-rock Preact starter project, powered by Webpack.
JavaScript
976
star
16

web-worker

Consistent Web Workers in browser and Node.
JavaScript
949
star
17

vhtml

Render JSX/Hyperscript to HTML strings, without VDOM 🌈
JavaScript
740
star
18

histore

🏬 200b key-value store backed by navigation state
JavaScript
677
star
19

optimize-plugin

Optimized Webpack Bundling for Everyone. Intro ‡️
JavaScript
659
star
20

undom

🍩 1kb minimally viable DOM Document implementation
JavaScript
654
star
21

asyncro

⛡️ Beautiful Array utilities for ESnext async/await ~
JavaScript
493
star
22

nextjs-preact-demo

Next.js 9.3 + Preact = 21kB
JavaScript
384
star
23

tags-input

πŸ”– <input type="tags"> like magic
JavaScript
328
star
24

linkstate

Bind events to state. Works with Preact and React.
JavaScript
296
star
25

preact-redux

➿ Preact integration for Redux (no shim needed!)
JavaScript
288
star
26

task-worklet

Task Worklet: explainer, polyfill and demos.
JavaScript
275
star
27

jsdom-worker

πŸ‘·β€β™€οΈ Use Web Workers in Jest / JSDOM 🌈
JavaScript
273
star
28

preact-worker-demo

Demo of preact rendering an entire app in a Web Worker.
JavaScript
217
star
29

preact-virtual-list

πŸ“‡ Virtual List that only renders visible items. Supports millions of rows.
JavaScript
215
star
30

jsxobj

Build JSON using JSX 🌈 (may contain blood magic)
JavaScript
214
star
31

preact-redux-example

πŸ” Preact + Redux Example Project
JavaScript
201
star
32

preact-markup

⚑ Render HTML5 as VDOM, with Components as Custom Elements!
JavaScript
195
star
33

simple-element-resize-detector

Observes element size changes using a hidden iframe
JavaScript
190
star
34

preact-mdl

πŸ’₯ A collection of Preact Components that encapsulate Google's Material Design Lite.
JavaScript
186
star
35

zero-to-preact

A Step-by-step Guide to Preact + Webpack 2, without boilerplate!
JavaScript
179
star
36

state-machine-component

βš™οΈ State machine -powered components in 250 bytes
JavaScript
177
star
37

preact-portal

πŸ“‘ Render Preact components in (a) SPACE 🌌 🌠
JavaScript
176
star
38

preact-photon

πŸš€ Beautiful desktop apps with Preact + Photon ❀️
JavaScript
173
star
39

preact-slots

πŸ•³ Render Preact trees into other Preact trees, like portals.
JavaScript
157
star
40

oss.ninja

πŸ‘©β€βš–οΈ Dynamic licenses for your projects - no more LICENSE.txt!
JavaScript
146
star
41

preact-cycle

♻️ Minimal functional Virtual DOM rendering using Preact 🚲
JavaScript
131
star
42

dropfox

🦊 πŸ“‚ A dropbox client powered by Preact, Electron and Photon
JavaScript
122
star
43

preact-scroll-viewport

Preact Component that renders homogeneous children only when visible
JavaScript
121
star
44

babel-preset-modernize

JavaScript
121
star
45

resource-router-middleware

🚴 Express REST resources as middleware mountable anywhere
JavaScript
120
star
46

object-diff-patch

JavaScript
103
star
47

preact-todomvc

πŸ’£ TodoMVC done in Preact. Under 6kb and fast.
JavaScript
102
star
48

restful-mongoose

🐦 Expose Mongoose models as RESTful Express resources.
JavaScript
90
star
49

modify-babel-preset

πŸ’« Create a modified babel preset based on an an existing preset.
JavaScript
85
star
50

preact-without-babel

🐎 How to use Preact in (native) ES2015, without Babel or JSX.
JavaScript
79
star
51

preact-shadow-root

πŸ•΄ Render a Preact subtree into the Shadow DOM.
JavaScript
72
star
52

linkref

Like Linked State, but for Refs. Works with Preact and React.
JavaScript
61
star
53

preact-css-transition-group

Apply CSS transitions when adding or removing Preact components/elements
JavaScript
61
star
54

proptypes

πŸ’‚β€β™‚οΈ React's PropTypes, as a standalone module.
JavaScript
59
star
55

preact-token-input

πŸ”– A text field that tokenizes input, for things like tags.
JavaScript
59
star
56

nectarine

πŸ‘ A mobile web / Android app for Peach! (peach.cool) ⚑
JavaScript
59
star
57

unified-element-properties-proposal

Unified Element Properties for the DOM
58
star
58

preact-jsx-chai

βœ… Add JSX assertions to Chai, with support for Preact Components.
JavaScript
56
star
59

preact-compat-example

🚀 Demo of preact-compat + react-toolbox to reduce build size by 95%.
JavaScript
52
star
60

preact-transition-group

transition-group ui component for preact
JavaScript
51
star
61

scroll-list

πŸ“œ An infinitely scrollable list/datagrid. Handles millions of rows.
JavaScript
48
star
62

preact-in-es3

🐴 How to use Preact without Babel, ES2015 or JSX.
JavaScript
46
star
63

rollup-plugin-preserve-shebang

Rollup plugin to automatically preserve shebangs in entry modules.
JavaScript
45
star
64

preact-cli-plugin-async

Preact CLI plugin that adds converts async/await to Promises.
JavaScript
44
star
65

preact-views

πŸ“Ί Named views for Preact, with easy-as-pie linking between them.
JavaScript
39
star
66

preact-richtextarea

πŸ“° A text field that supports HTML editing. πŸ“
JavaScript
39
star
67

react-router-4-test

Did you know you can use React Router with Preact, no -compat?
JavaScript
35
star
68

element-worklet

34
star
69

documentation-viewer

πŸ“œ Hosted viewer for documentation.js JSON output.
JavaScript
34
star
70

sleeper

😴 REST abstraction so easy you could use it with your eyes closed. πŸ’€
JavaScript
30
star
71

neatime

Returns a simple relative time string.
JavaScript
30
star
72

babel-preset-preact

Babel preset to transform JSX into h() calls
JavaScript
30
star
73

ama

Ask me stuff
28
star
74

htmlParser

Simple JavaScript HTML parser.
JavaScript
27
star
75

precharts

Just Recharts pre-aliased for Preact.
JavaScript
27
star
76

object-shape

Get a description of a JS object's shape.
JavaScript
24
star
77

eslint-config-developit

developit's generic eslint config for libraries
JavaScript
21
star
78

peach.cool

πŸ‘ JavaScript library for Peach (peach.cool) ⚑
JavaScript
21
star
79

progress-spinner

⌚ A simple, CSS-only indeterminate spinner custom element.
HTML
21
star
80

rollup-plugin-postprocess

🎞 Find & replace postprocessing for Rollup output
JavaScript
18
star
81

desky

18
star
82

jasonformat.com

My blog
JavaScript
18
star
83

preact-tap-event-plugin

☝️ onTouchTap for preact
JavaScript
17
star
84

preact-svg

[DEPRECATED] 🎨 Use inline <svg> in Preact 4 and prior. 🌷
JavaScript
16
star
85

preact-styled-jsx-demo

Preact + styled-jsx = πŸ’ž
JavaScript
16
star
86

preact-vite-template

JavaScript
15
star
87

espz

JavaScript
13
star
88

microbundle-2

JavaScript
13
star
89

hazelnut

🌰 Tiny inline AMD registry.
JavaScript
12
star
90

puredom

πŸ’² Fast, chainable and exstensible JavaScript library for building web applications.
JavaScript
11
star
91

request-easy-cache

🐎 A simple, configurable & instantiable caching wrapper around request.
JavaScript
11
star
92

templeton

πŸ’ͺ Templating like the other ones, but not at all like the other ones.
JavaScript
10
star
93

bamboo-status-svg

A web service that generates build badges for Bamboo plans.
JavaScript
9
star
94

ford.js

πŸ‘” The library nobody wants but that is for some reason still mayor.
JavaScript
8
star
95

jasonp

An itty bitty JSONP module
JavaScript
7
star
96

browser-nativefs

Native File System API with legacy fallback in the browser
JavaScript
7
star
97

strip-dom-whitespace

Traverses the DOM to strip whitespace-only Text nodes
JavaScript
6
star
98

picomarkdown

Converts basic markdown to HTML.
JavaScript
6
star
99

babel-preset-es2015-minimal

πŸ’„ Babel's es2015 preset in loose mode without frills.
JavaScript
5
star
100

esbench

ESBench Feedback (future public repo)
4
star