### Install Development Dependencies Source: https://github.com/developit/unfetch/blob/main/README.md Run this command to install the necessary tools for development. Ensure you have completed the previous steps of forking, cloning, and navigating to the project directory. ```bash npm install ``` -------------------------------- ### GET and POST requests with unfetch Source: https://context7.com/developit/unfetch/llms.txt Demonstrates making GET and POST requests using the unfetch library. Includes JSON parsing and custom headers for POST requests. Ensure unfetch is imported. ```javascript import fetch from 'unfetch'; // GET + JSON parsing fetch('/api/users/1') .then(res => { if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`); return res.json(); }) .then(user => console.log(user)) // { id: 1, name: "Alice" } .catch(err => console.error(err)); // POST with JSON body and custom headers fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Api-Key': 'secret' }, body: JSON.stringify({ name: 'Bob', role: 'admin' }), }) .then(res => res.json()) .then(created => console.log(created)); // { id: 2, name: "Bob", role: "admin" } ``` -------------------------------- ### Install unfetch via npm Source: https://github.com/developit/unfetch/blob/main/README.md Use npm to install unfetch for your Node.js project. This is the first step to using unfetch in your development workflow. ```sh npm i unfetch ``` -------------------------------- ### Install Isomorphic Unfetch Source: https://github.com/developit/unfetch/blob/main/packages/isomorphic-unfetch/readme.md Install the package using npm. This package requires Node.js version 12.20.0 or higher. ```sh npm i isomorphic-unfetch ``` -------------------------------- ### Auto-installing Polyfill via CDN Source: https://context7.com/developit/unfetch/llms.txt Include this script tag to conditionally install unfetch as window.fetch in browsers lacking native support. It ensures fetch is available globally. ```html ``` -------------------------------- ### Simple GET Request with unfetch Source: https://github.com/developit/unfetch/blob/main/README.md Perform a basic GET request and retrieve the response as text. This demonstrates the fundamental usage of unfetch for fetching resources. ```js // simple GET request: fetch('/foo') .then( r => r.text() ) .then( txt => console.log(txt) ) ``` -------------------------------- ### Usage as a Global Polyfill Source: https://github.com/developit/unfetch/blob/main/packages/isomorphic-unfetch/readme.md Import the library to install fetch globally, making it available without explicit import. This is useful for polyfilling environments where fetch is not natively available. ```javascript import "isomorphic-unfetch"; // "fetch" is now installed globally if it wasn't already available fetch("/foo.json") .then((r) => r.json()) .then((data) => { console.log(data); }); ``` -------------------------------- ### Complex POST Request with unfetch Source: https://github.com/developit/unfetch/blob/main/README.md Make a POST request with JSON data and custom headers. This example shows how to send data and handle redirects based on response headers. ```js // 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(); }) ``` -------------------------------- ### Usage as a Ponyfill Source: https://github.com/developit/unfetch/blob/main/packages/isomorphic-unfetch/readme.md Use the imported fetch function as a ponyfill to make network requests. This example demonstrates fetching JSON data. ```javascript import fetch from "isomorphic-unfetch"; fetch("/foo.json") .then((r) => r.json()) .then((data) => { console.log(data); }); ``` -------------------------------- ### Handling HTTP Errors Source: https://github.com/developit/unfetch/blob/main/README.md Example of how to handle non-2xx HTTP status codes, as the fetch Promise only rejects on network failures. ```APIDOC ## Caveats * 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: ```javascript 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); }); ``` ``` -------------------------------- ### Accessing response headers with unfetch Source: https://context7.com/developit/unfetch/llms.txt Demonstrates how to use the `headers` object on an `UnfetchResponse` to access header values. Supports `get()`, `has()`, `keys()`, and `entries()`. Note that mutable operations are not implemented. ```javascript import fetch from 'unfetch'; fetch('/api/items') .then(res => { const h = res.headers; console.log(h.get('content-type')); // "application/json" console.log(h.get('x-request-id')); // "abc-123" or null console.log(h.has('authorization')); // false // Enumerate all headers console.log(h.keys()); // ["content-type", "x-request-id", "cache-control"] console.log(h.entries()); // [["content-type","application/json"],["x-request-id","abc-123"],["cache-control","no-store"]] return res.json(); }); ``` -------------------------------- ### Build Project Source: https://github.com/developit/unfetch/blob/main/README.md Execute this command to build the project and verify that your changes do not significantly increase the output size. This is a critical step for maintaining project performance. ```bash npm run build ``` -------------------------------- ### Test Project Source: https://github.com/developit/unfetch/blob/main/README.md Run this command to execute the project's test suite and ensure that your changes have not introduced any regressions or broken existing functionality. ```bash npm test ``` -------------------------------- ### Use unfetch as a Polyfill Source: https://github.com/developit/unfetch/blob/main/README.md Import the polyfill to automatically replace the global `window.fetch` if it's not supported. This is useful for hotlinking from CDNs. ```js import 'unfetch/polyfill' // fetch is now available globally! fetch('/foo.json') .then( r => r.json() ) .then( data => console.log(data) ) ``` ```html ``` -------------------------------- ### Auto-installing Polyfill via npm Source: https://context7.com/developit/unfetch/llms.txt Import 'unfetch/polyfill' once at your application's entry point to make fetch globally available. This is ideal for bundles requiring full backwards compatibility. ```javascript // Via npm — import once at your app entry point import 'unfetch/polyfill'; // fetch is now globally available throughout the app fetch('/api/products') .then(res => res.json()) .then(products => renderList(products)); ``` -------------------------------- ### fetch(url, options) Source: https://context7.com/developit/unfetch/llms.txt The core ponyfill function that mimics the standard fetch API. It takes a URL and an optional options object and returns a Promise that resolves with an UnfetchResponse. ```APIDOC ## fetch(url, options) — Core ponyfill function ### Description The default export is a function with the signature `fetch(url: string | URL, options?: UnfetchRequestInit): Promise`. It opens an `XMLHttpRequest` internally and resolves the returned Promise with a response object when the request completes. Supported `options` fields are `method`, `headers` (plain object), `credentials` (`"include"` to send cookies), and `body`. Any unsupported standard `RequestInit` fields (`signal`, `mode`, `cache`, `redirect`, etc.) are silently ignored. ### Method `fetch` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```js import fetch from 'unfetch'; // GET + JSON parsing fetch('/api/users/1') .then(res => { if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`); return res.json(); }) .then(user => console.log(user)) // { id: 1, name: "Alice" } .catch(err => console.error(err)); // POST with JSON body and custom headers fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Api-Key': 'secret' }, body: JSON.stringify({ name: 'Bob', role: 'admin' }), }) .then(res => res.json()) .then(created => console.log(created)); // { id: 2, name: "Bob", role: "admin" } // Send cookies with cross-origin request fetch('https://api.example.com/profile', { credentials: 'include', }) .then(res => res.text()) .then(html => console.log(html)); ``` ### Response #### Success Response (200) An `UnfetchResponse` object with properties like `ok`, `status`, `statusText`, `url`, and methods `text()`, `json()`, `blob()`. #### Response Example ```js // Example response object structure (actual data depends on the request) { ok: true, status: 200, statusText: "OK", url: "/api/users/1", // Methods like text(), json(), blob() return Promises } ``` ``` -------------------------------- ### Sending cookies with unfetch Source: https://context7.com/developit/unfetch/llms.txt Shows how to include credentials (cookies) in a cross-origin request using unfetch. The `credentials: 'include'` option is required. ```javascript import fetch from 'unfetch'; // Send cookies with cross-origin request fetch('https://api.example.com/profile', { credentials: 'include', }) .then(res => res.text()) .then(html => console.log(html)); ``` -------------------------------- ### Use unfetch as a Ponyfill Source: https://github.com/developit/unfetch/blob/main/README.md Import unfetch directly into your modules to use it without affecting the global scope. This is the recommended approach when using module bundlers. ```js // 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) ) ``` -------------------------------- ### UnfetchResponse object properties and methods Source: https://context7.com/developit/unfetch/llms.txt Illustrates how to access properties like `ok`, `status`, `statusText`, and `url` from the `UnfetchResponse` object. Also shows how to use `clone()` and body-reading methods like `text()` and `json()`. Remember that response bodies can only be read once per clone. ```javascript import fetch from 'unfetch'; fetch('/api/data') .then(res => { console.log(res.ok); // true console.log(res.status); // 200 console.log(res.statusText); // "OK" console.log(res.url); // "/api/data" (or redirect target) // Clone before consuming body (body can only be read once per clone) const copy = res.clone(); copy.text().then(raw => console.log('raw:', raw)); return res.json(); }) .then(data => console.log(data)); // Handling non-2xx as errors fetch('/api/missing') .then(res => { if (!res.ok) { const err = new Error(res.statusText); err.status = res.status; throw err; } return res.json(); }) .catch(err => console.error(`${err.status} – ${err.message}`)); // 404 – Not Found ``` -------------------------------- ### Commit Changes Source: https://github.com/developit/unfetch/blob/main/README.md Use this command to stage and commit your changes with a descriptive message. Replace 'Add some feature' with a concise summary of your modifications. ```bash git commit -am 'Add some feature' ``` -------------------------------- ### fetch(url, options) Source: https://github.com/developit/unfetch/blob/main/README.md The core function for making HTTP requests. It takes a URL and an options object, returning a Promise that resolves to a response. ```APIDOC ## `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](#caveats), 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. ``` -------------------------------- ### Import Fetch (ES6 Modules) Source: https://github.com/developit/unfetch/blob/main/packages/isomorphic-unfetch/readme.md Import the fetch function when using ES6 modules in your project. ```javascript // using ES6 modules import fetch from "isomorphic-unfetch"; ``` -------------------------------- ### Import Fetch (CommonJS Modules) Source: https://github.com/developit/unfetch/blob/main/packages/isomorphic-unfetch/readme.md Import the fetch function when using CommonJS modules in your project. ```javascript // using CommonJS modules const fetch = require("isomorphic-unfetch"); ``` -------------------------------- ### Isomorphic unfetch for Browser and Node.js Source: https://context7.com/developit/unfetch/llms.txt Use 'isomorphic-unfetch' to automatically select the correct fetch implementation based on the environment. It assigns the resolved function to global.fetch and handles protocol-relative URLs in Node.js. ```javascript // Works identically in both browser and Node.js import fetch from 'isomorphic-unfetch'; // CommonJS also supported // const fetch = require('isomorphic-unfetch'); async function getUser(id) { const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`); if (!res.ok) throw new Error(`Failed: ${res.status}`); return res.json(); } getUser(1).then(user => console.log(user.name)); // "Leanne Graham" // SSR example — same code runs in Next.js server and browser async function getServerSideProps() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data } }; } ``` -------------------------------- ### Response Methods and Attributes Source: https://github.com/developit/unfetch/blob/main/README.md Methods and attributes available on the response object returned by the fetch function for handling the response data and status. ```APIDOC ## `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](https://fetch.spec.whatwg.org/#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`](https://fetch.spec.whatwg.org/#headers), 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. ``` -------------------------------- ### Include Credentials in Fetch Request Source: https://github.com/developit/unfetch/blob/main/README.md Use the 'credentials' option set to 'include' to allow fetch requests to send and receive cookies, which is necessary for both CORS and same-origin requests that rely on session management. ```javascript fetch('/users', { credentials: 'include' }); ``` -------------------------------- ### Push Changes to Branch Source: https://github.com/developit/unfetch/blob/main/README.md After committing, push your changes to your feature branch on the remote repository. This prepares your changes for a pull request. ```bash git push origin my-new-feature ``` -------------------------------- ### response.headers Source: https://context7.com/developit/unfetch/llms.txt Provides read-only access to the response headers. ```APIDOC ### `response.headers` — UnfetchHeaders interface ### Description The `headers` property on a response is a lightweight object that provides read-only access to response headers. It supports four methods: `get(key)` returns the header value string or `null`; `has(key)` returns a boolean; `keys()` returns an array of all lowercase header name strings; `entries()` returns an array of `[key, value]` pairs. Mutable operations (`set`, `append`, `delete`, `forEach`, iteration via `Symbol.iterator`) are not implemented. ### Methods - **get(key: string)**: Returns the header value for the given key, or `null` if not found. - **has(key: string)**: Returns `true` if the header exists, `false` otherwise. - **keys()**: Returns an array of all header names (lowercase). - **entries()**: Returns an array of `[key, value]` pairs for all headers. ### Request Example ```js import fetch from 'unfetch'; fetch('/api/items') .then(res => { const h = res.headers; console.log(h.get('content-type')); // "application/json" console.log(h.get('x-request-id')); // "abc-123" or null console.log(h.has('authorization')); // false // Enumerate all headers console.log(h.keys()); // ["content-type", "x-request-id", "cache-control"] console.log(h.entries()); // [["content-type","application/json"],["x-request-id","abc-123"],["cache-control","no-store"]] return res.json(); }); ``` ### Response #### Success Response (200) The `headers` object on the `UnfetchResponse`. #### Response Example ```js // Example headers object structure { get: (key) => string | null, has: (key) => boolean, keys: () => string[], entries: () => [string, string][] } ``` ``` -------------------------------- ### TypeScript Usage with unfetch Source: https://context7.com/developit/unfetch/llms.txt Leverage TypeScript declarations for type safety. Unfetch provides `UnfetchRequestInit` and `UnfetchResponse` types, marking unsupported features as `never` to catch compile-time errors. Isomorphic usage is covered by `Unfetch.Response` and `Unfetch.IsomorphicResponse`. ```typescript import fetch, { UnfetchRequestInit, UnfetchResponse } from 'unfetch'; interface User { id: number; name: string; email: string; } async function createUser(payload: Omit): Promise { const options: UnfetchRequestInit = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }; const res: UnfetchResponse = await fetch('/api/users', options); if (!res.ok) { throw new Error(`${res.status} ${res.statusText}`); } return res.json() as Promise; } // TypeScript will error on unsupported options at compile time: // fetch('/foo', { signal: new AbortController().signal }); // ❌ Type error: 'signal' is 'never' // fetch('/foo', { mode: 'cors' }); // ❌ Type error: 'mode' is 'never' createUser({ name: 'Carol', email: 'carol@example.com' }) .then(u => console.log(`Created user #${u.id}`)); ``` -------------------------------- ### UnfetchResponse Source: https://context7.com/developit/unfetch/llms.txt Represents the response to a fetch request. It provides information about the request status and allows reading the response body. ```APIDOC ### `UnfetchResponse` — Response object ### Description Every resolved Promise yields an `UnfetchResponse` object. It exposes `ok` (boolean, true for 2xx), `status` (number), `statusText` (string), `url` (final URL after redirect), and the body-reading methods `text()`, `json()`, and `blob()` — each returning a Promise. `clone()` returns a new response object with identical shape and data. Note that `arrayBuffer()`, `formData()`, `body` (stream), `bodyUsed`, `redirected`, and `type` are **not** supported. ### Properties - **ok** (boolean) - True for successful (2xx) status codes. - **status** (number) - The HTTP status code. - **statusText** (string) - The HTTP status text. - **url** (string) - The final URL of the response after any redirects. ### Methods - **text()**: Returns a Promise that resolves with the response body as text. - **json()**: Returns a Promise that resolves with the response body parsed as JSON. - **blob()**: Returns a Promise that resolves with the response body as a Blob. - **clone()**: Returns a new `UnfetchResponse` object with the same data. ### Request Example ```js import fetch from 'unfetch'; fetch('/api/data') .then(res => { console.log(res.ok); // true console.log(res.status); // 200 console.log(res.statusText); // "OK" console.log(res.url); // "/api/data" (or redirect target) // Clone before consuming body (body can only be read once per clone) const copy = res.clone(); copy.text().then(raw => console.log('raw:', raw)); return res.json(); }) .then(data => console.log(data)); // Handling non-2xx as errors fetch('/api/missing') .then(res => { if (!res.ok) { const err = new Error(res.statusText); err.status = res.status; throw err; } return res.json(); }) .catch(err => console.error(`${err.status} – ${err.message}`)); // 404 – Not Found ``` ### Response #### Success Response (200) An `UnfetchResponse` object as described above. #### Response Example ```js // Example response object structure { ok: true, status: 200, statusText: "OK", url: "/api/data", // Methods: text(), json(), blob(), clone() } ``` ``` -------------------------------- ### Handle HTTP Errors in Fetch Response Source: https://github.com/developit/unfetch/blob/main/README.md By default, fetch Promises do not reject on HTTP error statuses (like 404 or 500). To handle these, implement a custom response handler that checks `response.ok` and rejects the Promise with an error for non-2xx status codes. ```javascript 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); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.