{"id":13432435,"url":"https://github.com/node-fetch/node-fetch","last_synced_at":"2025-11-12T21:40:43.346Z","repository":{"id":26400223,"uuid":"29849956","full_name":"node-fetch/node-fetch","owner":"node-fetch","description":"A light-weight module that brings the Fetch API to Node.js","archived":false,"fork":false,"pushed_at":"2024-08-13T22:17:04.000Z","size":1268,"stargazers_count":8844,"open_issues_count":224,"forks_count":1051,"subscribers_count":89,"default_branch":"main","last_synced_at":"2025-11-11T23:38:50.930Z","etag":null,"topics":["fetch","fetch-api","hacktoberfest","http","http-client","node-fetch","promise","spec-compliant","stream","whatwg","whatwg-fetch"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/node-fetch.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"node-fetch","patreon":null,"open_collective":"node-fetch","ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null}},"created_at":"2015-01-26T07:29:26.000Z","updated_at":"2025-11-11T19:53:26.000Z","dependencies_parsed_at":"2023-09-29T08:54:24.080Z","dependency_job_id":"7e33693a-238c-4f0b-939f-0ec6afd5cb5e","html_url":"https://github.com/node-fetch/node-fetch","commit_stats":{"total_commits":596,"total_committers":121,"mean_commits":4.925619834710743,"dds":0.7600671140939598,"last_synced_commit":"8b3320d2a7c07bce4afc6b2bf6c3bbddda85b01f"},"previous_names":["bitinn/node-fetch"],"tags_count":76,"template":false,"template_full_name":null,"purl":"pkg:github/node-fetch/node-fetch","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/node-fetch%2Fnode-fetch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/node-fetch%2Fnode-fetch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/node-fetch%2Fnode-fetch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/node-fetch%2Fnode-fetch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/node-fetch","download_url":"https://codeload.github.com/node-fetch/node-fetch/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/node-fetch%2Fnode-fetch/sbom","scorecard":{"id":240298,"data":{"date":"2025-08-11","repo":{"name":"github.com/node-fetch/node-fetch","commit":"8b3320d2a7c07bce4afc6b2bf6c3bbddda85b01f"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":5.4,"checks":[{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Code-Review","score":10,"reason":"all changesets reviewed","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Security-Policy","score":9,"reason":"security policy file detected","details":["Info: security policy file detected: SECURITY.md:1","Info: Found linked content: SECURITY.md:1","Warn: One or no descriptive hints of disclosure, vulnerability, and/or timelines in security policy","Info: Found text in security policy: SECURITY.md:1"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Warn: no topLevel permission defined: .github/workflows/ci.yml:1","Warn: no topLevel permission defined: .github/workflows/lint.yml:1","Warn: no topLevel permission defined: .github/workflows/release.yml:1","Warn: no topLevel permission defined: .github/workflows/types.yml:1","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Pinned-Dependencies","score":0,"reason":"dependency not pinned by hash detected -- score normalized to 0","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:32: update your workflow using https://app.stepsecurity.io/secureworkflow/node-fetch/node-fetch/ci.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:34: update your workflow using https://app.stepsecurity.io/secureworkflow/node-fetch/node-fetch/ci.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/lint.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/node-fetch/node-fetch/lint.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/lint.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/node-fetch/node-fetch/lint.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/node-fetch/node-fetch/release.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/release.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/node-fetch/node-fetch/release.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/types.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/node-fetch/node-fetch/types.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/types.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/node-fetch/node-fetch/types.yml/main?enable=pin","Warn: npmCommand not pinned by hash: .github/workflows/ci.yml:39","Warn: npmCommand not pinned by hash: .github/workflows/lint.yml:20","Warn: npmCommand not pinned by hash: .github/workflows/types.yml:18","Info:   0 out of   8 GitHub-owned GitHubAction dependencies pinned","Info:   0 out of   3 npmCommand dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE.md:0","Info: FSF or OSI recognized license: MIT License: LICENSE.md:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":-1,"reason":"internal error: error during branchesHandler.setup: internal error: githubv4.Query: Resource not accessible by integration","details":null,"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 30 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}}]},"last_synced_at":"2025-08-17T06:35:17.780Z","repository_id":26400223,"created_at":"2025-08-17T06:35:17.781Z","updated_at":"2025-08-17T06:35:17.781Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":284115869,"owners_count":26949957,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-11-12T02:00:06.336Z","response_time":59,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fetch","fetch-api","hacktoberfest","http","http-client","node-fetch","promise","spec-compliant","stream","whatwg","whatwg-fetch"],"created_at":"2024-07-31T02:01:11.570Z","updated_at":"2025-11-12T21:40:43.322Z","avatar_url":"https://github.com/node-fetch.png","language":"JavaScript","readme":"\u003cdiv align=\"center\"\u003e\n\t\u003cimg src=\"docs/media/Banner.svg\" alt=\"Node Fetch\"/\u003e\n\t\u003cbr\u003e\n\t\u003cp\u003eA light-weight module that brings \u003ca href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\"\u003eFetch API\u003c/a\u003e to Node.js.\u003c/p\u003e\n\t\u003ca href=\"https://github.com/node-fetch/node-fetch/actions\"\u003e\u003cimg src=\"https://github.com/node-fetch/node-fetch/workflows/CI/badge.svg?branch=master\" alt=\"Build status\"\u003e\u003c/a\u003e\n\t\u003ca href=\"https://coveralls.io/github/node-fetch/node-fetch\"\u003e\u003cimg src=\"https://img.shields.io/coveralls/github/node-fetch/node-fetch\" alt=\"Coverage status\"\u003e\u003c/a\u003e\n\t\u003ca href=\"https://packagephobia.now.sh/result?p=node-fetch\"\u003e\u003cimg src=\"https://badgen.net/packagephobia/install/node-fetch\" alt=\"Current version\"\u003e\u003c/a\u003e\n\t\u003ca href=\"https://www.npmjs.com/package/node-fetch\"\u003e\u003cimg src=\"https://img.shields.io/npm/v/node-fetch\" alt=\"Install size\"\u003e\u003c/a\u003e\n\t\u003ca href=\"https://github.com/sindresorhus/awesome-nodejs\"\u003e\u003cimg src=\"https://awesome.re/mentioned-badge.svg\" alt=\"Mentioned in Awesome Node.js\"\u003e\u003c/a\u003e\n\t\u003ca href=\"https://discord.gg/Zxbndcm\"\u003e\u003cimg src=\"https://img.shields.io/discord/619915844268326952?color=%237289DA\u0026label=Discord\" alt=\"Discord\"\u003e\u003c/a\u003e\n\t\u003cbr\u003e\n\t\u003cbr\u003e\n\t\u003cb\u003eConsider supporting us on our Open Collective:\u003c/b\u003e\n\t\u003cbr\u003e\n\t\u003cbr\u003e\n\t\u003ca href=\"https://opencollective.com/node-fetch\"\u003e\u003cimg src=\"https://opencollective.com/node-fetch/donate/button.png?color=blue\" alt=\"Open Collective\"\u003e\u003c/a\u003e\n\u003c/div\u003e\n\n---\n\n**You might be looking for the [v2 docs](https://github.com/node-fetch/node-fetch/tree/2.x#readme)**\n\n\u003c!-- TOC --\u003e\n\n- [Motivation](#motivation)\n- [Features](#features)\n- [Difference from client-side fetch](#difference-from-client-side-fetch)\n- [Installation](#installation)\n- [Loading and configuring the module](#loading-and-configuring-the-module)\n- [Upgrading](#upgrading)\n- [Common Usage](#common-usage)\n\t- [Plain text or HTML](#plain-text-or-html)\n\t- [JSON](#json)\n\t- [Simple Post](#simple-post)\n\t- [Post with JSON](#post-with-json)\n\t- [Post with form parameters](#post-with-form-parameters)\n\t- [Handling exceptions](#handling-exceptions)\n\t- [Handling client and server errors](#handling-client-and-server-errors)\n\t- [Handling cookies](#handling-cookies)\n- [Advanced Usage](#advanced-usage)\n\t- [Streams](#streams)\n\t- [Accessing Headers and other Metadata](#accessing-headers-and-other-metadata)\n\t- [Extract Set-Cookie Header](#extract-set-cookie-header)\n\t- [Post data using a file](#post-data-using-a-file)\n\t- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)\n- [API](#api)\n\t- [fetch(url[, options])](#fetchurl-options)\n\t- [Options](#options)\n\t\t- [Default Headers](#default-headers)\n\t\t- [Custom Agent](#custom-agent)\n\t\t- [Custom highWaterMark](#custom-highwatermark)\n\t\t- [Insecure HTTP Parser](#insecure-http-parser)\n\t- [Class: Request](#class-request)\n\t\t- [new Request(input[, options])](#new-requestinput-options)\n\t- [Class: Response](#class-response)\n\t\t- [new Response([body[, options]])](#new-responsebody-options)\n\t\t- [response.ok](#responseok)\n\t\t- [response.redirected](#responseredirected)\n\t\t- [response.type](#responsetype)\n\t- [Class: Headers](#class-headers)\n\t\t- [new Headers([init])](#new-headersinit)\n\t- [Interface: Body](#interface-body)\n\t\t- [body.body](#bodybody)\n\t\t- [body.bodyUsed](#bodybodyused)\n\t\t- [body.arrayBuffer()](#bodyarraybuffer)\n\t\t- [body.blob()](#bodyblob)\n\t\t- [body.formData()](#formdata)\n\t\t- [body.json()](#bodyjson)\n\t\t- [body.text()](#bodytext)\n\t- [Class: FetchError](#class-fetcherror)\n\t- [Class: AbortError](#class-aborterror)\n- [TypeScript](#typescript)\n- [Acknowledgement](#acknowledgement)\n- [Team](#team)\n\t\t\t\t- [Former](#former)\n- [License](#license)\n\n\u003c!-- /TOC --\u003e\n\n## Motivation\n\nInstead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.\n\nSee Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).\n\n## Features\n\n- Stay consistent with `window.fetch` API.\n- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.\n- Use native promise and async functions.\n- Use native Node streams for body, on both request and response.\n- Decode content encoding (gzip/deflate/brotli) properly, and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.\n- Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.\n\n## Difference from client-side fetch\n\n- See known differences:\n\t- [As of v3.x](docs/v3-LIMITS.md)\n\t- [As of v2.x](docs/v2-LIMITS.md)\n- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.\n- Pull requests are welcomed too!\n\n## Installation\n\nCurrent stable release (`3.x`) requires at least Node.js 12.20.0.\n\n```sh\nnpm install node-fetch\n```\n\n## Loading and configuring the module\n\n### ES Modules (ESM)\n\n```js\nimport fetch from 'node-fetch';\n```\n\n### CommonJS\n\n`node-fetch` from v3 is an ESM-only module - you are not able to import it with `require()`.\n\nIf you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2.\n\n```sh\nnpm install node-fetch@2\n```\n\nAlternatively, you can use the async `import()` function from CommonJS to load `node-fetch` asynchronously:\n\n```js\n// mod.cjs\nconst fetch = (...args) =\u003e import('node-fetch').then(({default: fetch}) =\u003e fetch(...args));\n```\n\n### Providing global access\n\nTo use `fetch()` without importing it, you can patch the `global` object in node:\n\n```js\n// fetch-polyfill.js\nimport fetch, {\n  Blob,\n  blobFrom,\n  blobFromSync,\n  File,\n  fileFrom,\n  fileFromSync,\n  FormData,\n  Headers,\n  Request,\n  Response,\n} from 'node-fetch'\n\nif (!globalThis.fetch) {\n  globalThis.fetch = fetch\n  globalThis.Headers = Headers\n  globalThis.Request = Request\n  globalThis.Response = Response\n}\n\n// index.js\nimport './fetch-polyfill'\n\n// ...\n```\n\n## Upgrading\n\nUsing an old version of node-fetch? Check out the following files:\n\n- [2.x to 3.x upgrade guide](docs/v3-UPGRADE-GUIDE.md)\n- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)\n- [Changelog](https://github.com/node-fetch/node-fetch/releases)\n\n## Common Usage\n\nNOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).\n\n### Plain text or HTML\n\n```js\nimport fetch from 'node-fetch';\n\nconst response = await fetch('https://github.com/');\nconst body = await response.text();\n\nconsole.log(body);\n```\n\n### JSON\n\n```js\nimport fetch from 'node-fetch';\n\nconst response = await fetch('https://api.github.com/users/github');\nconst data = await response.json();\n\nconsole.log(data);\n```\n\n### Simple Post\n\n```js\nimport fetch from 'node-fetch';\n\nconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});\nconst data = await response.json();\n\nconsole.log(data);\n```\n\n### Post with JSON\n\n```js\nimport fetch from 'node-fetch';\n\nconst body = {a: 1};\n\nconst response = await fetch('https://httpbin.org/post', {\n\tmethod: 'post',\n\tbody: JSON.stringify(body),\n\theaders: {'Content-Type': 'application/json'}\n});\nconst data = await response.json();\n\nconsole.log(data);\n```\n\n### Post with form parameters\n\n`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.\n\nNOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:\n\n```js\nimport fetch from 'node-fetch';\n\nconst params = new URLSearchParams();\nparams.append('a', 1);\n\nconst response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});\nconst data = await response.json();\n\nconsole.log(data);\n```\n\n### Handling exceptions\n\nNOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.\n\nWrapping the fetch function into a `try/catch` block will catch _all_ exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.\n\n```js\nimport fetch from 'node-fetch';\n\ntry {\n\tawait fetch('https://domain.invalid/');\n} catch (error) {\n\tconsole.log(error);\n}\n```\n\n### Handling client and server errors\n\nIt is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:\n\n```js\nimport fetch from 'node-fetch';\n\nclass HTTPResponseError extends Error {\n\tconstructor(response) {\n\t\tsuper(`HTTP Error Response: ${response.status} ${response.statusText}`);\n\t\tthis.response = response;\n\t}\n}\n\nconst checkStatus = response =\u003e {\n\tif (response.ok) {\n\t\t// response.status \u003e= 200 \u0026\u0026 response.status \u003c 300\n\t\treturn response;\n\t} else {\n\t\tthrow new HTTPResponseError(response);\n\t}\n}\n\nconst response = await fetch('https://httpbin.org/status/400');\n\ntry {\n\tcheckStatus(response);\n} catch (error) {\n\tconsole.error(error);\n\n\tconst errorBody = await error.response.text();\n\tconsole.error(`Error body: ${errorBody}`);\n}\n```\n\n### Handling cookies\n\nCookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See [Extract Set-Cookie Header](#extract-set-cookie-header) for details.\n\n## Advanced Usage\n\n### Streams\n\nThe \"Node.js way\" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.\n\n```js\nimport {createWriteStream} from 'node:fs';\nimport {pipeline} from 'node:stream';\nimport {promisify} from 'node:util'\nimport fetch from 'node-fetch';\n\nconst streamPipeline = promisify(pipeline);\n\nconst response = await fetch('https://github.githubassets.com/images/modules/logos_page/Octocat.png');\n\nif (!response.ok) throw new Error(`unexpected response ${response.statusText}`);\n\nawait streamPipeline(response.body, createWriteStream('./octocat.png'));\n```\n\nIn Node.js 14 you can also use async iterators to read `body`; however, be careful to catch\nerrors -- the longer a response runs, the more likely it is to encounter an error.\n\n```js\nimport fetch from 'node-fetch';\n\nconst response = await fetch('https://httpbin.org/stream/3');\n\ntry {\n\tfor await (const chunk of response.body) {\n\t\tconsole.dir(JSON.parse(chunk.toString()));\n\t}\n} catch (err) {\n\tconsole.error(err.stack);\n}\n```\n\nIn Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams\ndid not mature until Node.js 14, so you need to do some extra work to ensure you handle errors\ndirectly from the stream and wait on it response to fully close.\n\n```js\nimport fetch from 'node-fetch';\n\nconst read = async body =\u003e {\n\tlet error;\n\tbody.on('error', err =\u003e {\n\t\terror = err;\n\t});\n\n\tfor await (const chunk of body) {\n\t\tconsole.dir(JSON.parse(chunk.toString()));\n\t}\n\n\treturn new Promise((resolve, reject) =\u003e {\n\t\tbody.on('close', () =\u003e {\n\t\t\terror ? reject(error) : resolve();\n\t\t});\n\t});\n};\n\ntry {\n\tconst response = await fetch('https://httpbin.org/stream/3');\n\tawait read(response.body);\n} catch (err) {\n\tconsole.error(err.stack);\n}\n```\n\n### Accessing Headers and other Metadata\n\n```js\nimport fetch from 'node-fetch';\n\nconst response = await fetch('https://github.com/');\n\nconsole.log(response.ok);\nconsole.log(response.status);\nconsole.log(response.statusText);\nconsole.log(response.headers.raw());\nconsole.log(response.headers.get('content-type'));\n```\n\n### Extract Set-Cookie Header\n\nUnlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.\n\n```js\nimport fetch from 'node-fetch';\n\nconst response = await fetch('https://example.com');\n\n// Returns an array of values, instead of a string of comma-separated values\nconsole.log(response.headers.raw()['set-cookie']);\n```\n\n### Post data using a file\n\n```js\nimport fetch, {\n  Blob,\n  blobFrom,\n  blobFromSync,\n  File,\n  fileFrom,\n  fileFromSync,\n} from 'node-fetch'\n\nconst mimetype = 'text/plain'\nconst blob = fileFromSync('./input.txt', mimetype)\nconst url = 'https://httpbin.org/post'\n\nconst response = await fetch(url, { method: 'POST', body: blob })\nconst data = await response.json()\n\nconsole.log(data)\n```\n\nnode-fetch comes with a spec-compliant [FormData] implementations for posting\nmultipart/form-data payloads\n\n```js\nimport fetch, { FormData, File, fileFrom } from 'node-fetch'\n\nconst httpbin = 'https://httpbin.org/post'\nconst formData = new FormData()\nconst binary = new Uint8Array([ 97, 98, 99 ])\nconst abc = new File([binary], 'abc.txt', { type: 'text/plain' })\n\nformData.set('greeting', 'Hello, world!')\nformData.set('file-upload', abc, 'new name.txt')\n\nconst response = await fetch(httpbin, { method: 'POST', body: formData })\nconst data = await response.json()\n\nconsole.log(data)\n```\n\nIf you for some reason need to post a stream coming from any arbitrary place,\nthen you can append a [Blob] or a [File] look-a-like item.\n\nThe minimum requirement is that it has:\n1. A `Symbol.toStringTag` getter or property that is either `Blob` or `File`\n2. A known size.\n3. And either a `stream()` method or a `arrayBuffer()` method that returns a ArrayBuffer.\n\nThe `stream()` must return any async iterable object as long as it yields Uint8Array (or Buffer)\nso Node.Readable streams and whatwg streams works just fine.\n\n```js\nformData.append('upload', {\n\t[Symbol.toStringTag]: 'Blob',\n\tsize: 3,\n  *stream() {\n    yield new Uint8Array([97, 98, 99])\n\t},\n\tarrayBuffer() {\n\t\treturn new Uint8Array([97, 98, 99]).buffer\n\t}\n}, 'abc.txt')\n```\n\n### Request cancellation with AbortSignal\n\nYou may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).\n\nAn example of timing out a request after 150ms could be achieved as the following:\n\n```js\nimport fetch, { AbortError } from 'node-fetch';\n\n// AbortController was added in node v14.17.0 globally\nconst AbortController = globalThis.AbortController || await import('abort-controller')\n\nconst controller = new AbortController();\nconst timeout = setTimeout(() =\u003e {\n\tcontroller.abort();\n}, 150);\n\ntry {\n\tconst response = await fetch('https://example.com', {signal: controller.signal});\n\tconst data = await response.json();\n} catch (error) {\n\tif (error instanceof AbortError) {\n\t\tconsole.log('request was aborted');\n\t}\n} finally {\n\tclearTimeout(timeout);\n}\n```\n\nSee [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.\n\n## API\n\n### fetch(url[, options])\n\n- `url` A string representing the URL for fetching\n- `options` [Options](#fetch-options) for the HTTP(S) request\n- Returns: \u003ccode\u003ePromise\u0026lt;[Response](#class-response)\u0026gt;\u003c/code\u003e\n\nPerform an HTTP(S) fetch.\n\n`url` should be an absolute URL, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.\n\n\u003ca id=\"fetch-options\"\u003e\u003c/a\u003e\n\n### Options\n\nThe default values are shown after each option key.\n\n```js\n{\n\t// These properties are part of the Fetch Standard\n\tmethod: 'GET',\n\theaders: {},            // Request headers. format is the identical to that accepted by the Headers constructor (see below)\n\tbody: null,             // Request body. can be null, or a Node.js Readable stream\n\tredirect: 'follow',     // Set to `manual` to extract redirect headers, `error` to reject redirect\n\tsignal: null,           // Pass an instance of AbortSignal to optionally abort requests\n\n\t// The following properties are node-fetch extensions\n\tfollow: 20,             // maximum redirect count. 0 to not follow redirect\n\tcompress: true,         // support gzip/deflate content encoding. false to disable\n\tsize: 0,                // maximum response body size in bytes. 0 to disable\n\tagent: null,            // http(s).Agent instance or function that returns an instance (see below)\n\thighWaterMark: 16384,   // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.\n\tinsecureHTTPParser: false\t// Use an insecure HTTP parser that accepts invalid HTTP headers when `true`.\n}\n```\n\n#### Default Headers\n\nIf no values are set, the following request headers will be sent automatically:\n\n| Header              | Value                                                  |\n| ------------------- | ------------------------------------------------------ |\n| `Accept-Encoding`   | `gzip, deflate, br` (when `options.compress === true`) |\n| `Accept`            | `*/*`                                                  |\n| `Content-Length`    | _(automatically calculated, if possible)_              |\n| `Host`              | _(host and port information from the target URI)_      |\n| `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_              |\n| `User-Agent`        | `node-fetch`                                           |\n\n\nNote: when `body` is a `Stream`, `Content-Length` is not set automatically.\n\n#### Custom Agent\n\nThe `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:\n\n- Support self-signed certificate\n- Use only IPv4 or IPv6\n- Custom DNS Lookup\n\nSee [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.\n\nIf no agent is specified, the default agent provided by Node.js is used. Note that [this changed in Node.js 19](https://github.com/nodejs/node/blob/4267b92604ad78584244488e7f7508a690cb80d0/lib/_http_agent.js#L564) to have `keepalive` true by default. If you wish to enable `keepalive` in an earlier version of Node.js, you can override the agent as per the following code sample. \n\nIn addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.\n\n```js\nimport http from 'node:http';\nimport https from 'node:https';\n\nconst httpAgent = new http.Agent({\n\tkeepAlive: true\n});\nconst httpsAgent = new https.Agent({\n\tkeepAlive: true\n});\n\nconst options = {\n\tagent: function(_parsedURL) {\n\t\tif (_parsedURL.protocol == 'http:') {\n\t\t\treturn httpAgent;\n\t\t} else {\n\t\t\treturn httpsAgent;\n\t\t}\n\t}\n};\n```\n\n\u003ca id=\"custom-highWaterMark\"\u003e\u003c/a\u003e\n\n#### Custom highWaterMark\n\nStream on Node.js have a smaller internal buffer size (16kB, aka `highWaterMark`) from client-side browsers (\u003e1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using `res.clone()`, it will hang with large response in Node.\n\nThe recommended way to fix this problem is to resolve cloned response in parallel:\n\n```js\nimport fetch from 'node-fetch';\n\nconst response = await fetch('https://example.com');\nconst r1 = response.clone();\n\nconst results = await Promise.all([response.json(), r1.text()]);\n\nconsole.log(results[0]);\nconsole.log(results[1]);\n```\n\nIf for some reason you don't like the solution above, since `3.x` you are able to modify the `highWaterMark` option:\n\n```js\nimport fetch from 'node-fetch';\n\nconst response = await fetch('https://example.com', {\n\t// About 1MB\n\thighWaterMark: 1024 * 1024\n});\n\nconst result = await res.clone().arrayBuffer();\nconsole.dir(result);\n```\n\n#### Insecure HTTP Parser\n\nPassed through to the `insecureHTTPParser` option on http(s).request. See [`http.request`](https://nodejs.org/api/http.html#http_http_request_url_options_callback) for more information.\n\n#### Manual Redirect\n\nThe `redirect: 'manual'` option for node-fetch is different from the browser \u0026 specification, which\nresults in an [opaque-redirect filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-opaque-redirect).\nnode-fetch gives you the typical [basic filtered response](https://fetch.spec.whatwg.org/#concept-filtered-response-basic) instead.\n\n```js\nimport fetch from 'node-fetch';\n\nconst response = await fetch('https://httpbin.org/status/301', { redirect: 'manual' });\n\nif (response.status === 301 || response.status === 302) {\n\tconst locationURL = new URL(response.headers.get('location'), response.url);\n\tconst response2 = await fetch(locationURL, { redirect: 'manual' });\n\tconsole.dir(response2);\n}\n```\n\n\u003ca id=\"class-request\"\u003e\u003c/a\u003e\n\n### Class: Request\n\nAn HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.\n\nDue to the nature of Node.js, the following properties are not implemented at this moment:\n\n- `type`\n- `destination`\n- `mode`\n- `credentials`\n- `cache`\n- `integrity`\n- `keepalive`\n\nThe following node-fetch extension properties are provided:\n\n- `follow`\n- `compress`\n- `counter`\n- `agent`\n- `highWaterMark`\n\nSee [options](#fetch-options) for exact meaning of these extensions.\n\n#### new Request(input[, options])\n\n\u003csmall\u003e_(spec-compliant)_\u003c/small\u003e\n\n- `input` A string representing a URL, or another `Request` (which will be cloned)\n- `options` [Options](#fetch-options) for the HTTP(S) request\n\nConstructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).\n\nIn most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.\n\n\u003ca id=\"class-response\"\u003e\u003c/a\u003e\n\n### Class: Response\n\nAn HTTP(S) response. This class implements the [Body](#iface-body) interface.\n\nThe following properties are not implemented in node-fetch at this moment:\n\n- `trailer`\n\n#### new Response([body[, options]])\n\n\u003csmall\u003e_(spec-compliant)_\u003c/small\u003e\n\n- `body` A `String` or [`Readable` stream][node-readable]\n- `options` A [`ResponseInit`][response-init] options dictionary\n\nConstructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).\n\nBecause Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.\n\n#### response.ok\n\n\u003csmall\u003e_(spec-compliant)_\u003c/small\u003e\n\nConvenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.\n\n#### response.redirected\n\n\u003csmall\u003e_(spec-compliant)_\u003c/small\u003e\n\nConvenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.\n\n#### response.type\n\n\u003csmall\u003e_(deviation from spec)_\u003c/small\u003e\n\nConvenience property representing the response's type. node-fetch only supports `'default'` and `'error'` and does not make use of [filtered responses](https://fetch.spec.whatwg.org/#concept-filtered-response).\n\n\u003ca id=\"class-headers\"\u003e\u003c/a\u003e\n\n### Class: Headers\n\nThis class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.\n\n#### new Headers([init])\n\n\u003csmall\u003e_(spec-compliant)_\u003c/small\u003e\n\n- `init` Optional argument to pre-fill the `Headers` object\n\nConstruct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.\n\n```js\n// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class\nimport {Headers} from 'node-fetch';\n\nconst meta = {\n\t'Content-Type': 'text/xml'\n};\nconst headers = new Headers(meta);\n\n// The above is equivalent to\nconst meta = [['Content-Type', 'text/xml']];\nconst headers = new Headers(meta);\n\n// You can in fact use any iterable objects, like a Map or even another Headers\nconst meta = new Map();\nmeta.set('Content-Type', 'text/xml');\nconst headers = new Headers(meta);\nconst copyOfHeaders = new Headers(headers);\n```\n\n\u003ca id=\"iface-body\"\u003e\u003c/a\u003e\n\n### Interface: Body\n\n`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.\n\n#### body.body\n\n\u003csmall\u003e_(deviation from spec)_\u003c/small\u003e\n\n- Node.js [`Readable` stream][node-readable]\n\nData are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].\n\n#### body.bodyUsed\n\n\u003csmall\u003e_(spec-compliant)_\u003c/small\u003e\n\n- `Boolean`\n\nA boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.\n\n#### body.arrayBuffer()\n\n#### body.formData()\n\n#### body.blob()\n\n#### body.json()\n\n#### body.text()\n\n`fetch` comes with methods to parse `multipart/form-data` payloads as well as\n`x-www-form-urlencoded` bodies using `.formData()` this comes from the idea that\nService Worker can intercept such messages before it's sent to the server to\nalter them. This is useful for anybody building a server so you can use it to\nparse \u0026 consume payloads.\n\n\u003cdetails\u003e\n\u003csummary\u003eCode example\u003c/summary\u003e\n\n```js\nimport http from 'node:http'\nimport { Response } from 'node-fetch'\n\nhttp.createServer(async function (req, res) {\n  const formData = await new Response(req, {\n    headers: req.headers // Pass along the boundary value\n  }).formData()\n  const allFields = [...formData]\n\n  const file = formData.get('uploaded-files')\n  const arrayBuffer = await file.arrayBuffer()\n  const text = await file.text()\n  const whatwgReadableStream = file.stream()\n\n  // other was to consume the request could be to do:\n  const json = await new Response(req).json()\n  const text = await new Response(req).text()\n  const arrayBuffer = await new Response(req).arrayBuffer()\n  const blob = await new Response(req, {\n    headers: req.headers // So that `type` inherits `Content-Type`\n  }.blob()\n})\n```\n\n\u003c/details\u003e\n\n\u003ca id=\"class-fetcherror\"\u003e\u003c/a\u003e\n\n### Class: FetchError\n\n\u003csmall\u003e_(node-fetch extension)_\u003c/small\u003e\n\nAn operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.\n\n\u003ca id=\"class-aborterror\"\u003e\u003c/a\u003e\n\n### Class: AbortError\n\n\u003csmall\u003e_(node-fetch extension)_\u003c/small\u003e\n\nAn Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.\n\n## TypeScript\n\n**Since `3.x` types are bundled with `node-fetch`, so you don't need to install any additional packages.**\n\nFor older versions please use the type definitions from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped):\n\n```sh\nnpm install --save-dev @types/node-fetch@2.x\n```\n\n## Acknowledgement\n\nThanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.\n\n## Team\n\n| [![David Frank](https://github.com/bitinn.png?size=100)](https://github.com/bitinn) | [![Jimmy Wärting](https://github.com/jimmywarting.png?size=100)](https://github.com/jimmywarting) | [![Antoni Kepinski](https://github.com/xxczaki.png?size=100)](https://github.com/xxczaki) | [![Richie Bendall](https://github.com/Richienb.png?size=100)](https://github.com/Richienb) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) |\n| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |\n| [David Frank](https://bitinn.net/)                                                  | [Jimmy Wärting](https://jimmy.warting.se/)                                                        | [Antoni Kepinski](https://kepinski.ch)                                                    | [Richie Bendall](https://www.richie-bendall.ml/)                                           | [Gregor Martynus](https://twitter.com/gr2m)                                         |\n\n###### Former\n\n- [Timothy Gu](https://github.com/timothygu)\n- [Jared Kantrowitz](https://github.com/jkantr)\n\n## License\n\n[MIT](LICENSE.md)\n\n[whatwg-fetch]: https://fetch.spec.whatwg.org/\n[response-init]: https://fetch.spec.whatwg.org/#responseinit\n[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams\n[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers\n[error-handling.md]: https://github.com/node-fetch/node-fetch/blob/master/docs/ERROR-HANDLING.md\n[FormData]: https://developer.mozilla.org/en-US/docs/Web/API/FormData\n[Blob]: https://developer.mozilla.org/en-US/docs/Web/API/Blob\n[File]: https://developer.mozilla.org/en-US/docs/Web/API/File\n","funding_links":["https://github.com/sponsors/node-fetch","https://opencollective.com/node-fetch"],"categories":["Packages","JavaScript","✨ Visual Example","Uncategorized","hacktoberfest","http","Programming Languages","包"],"sub_categories":["HTTP","Uncategorized","JavaScript"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnode-fetch%2Fnode-fetch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnode-fetch%2Fnode-fetch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnode-fetch%2Fnode-fetch/lists"}