Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

node-fetch retrieves a webpage’s HTTP response; pair it with an HTML parser such as Cheerio to extract data. The key distinction is that fetching HTML is not the same as running a browser: node-fetch does not execute page JavaScript. For ordinary server-rendered pages, the workflow is fetch, check the HTTP status, read the response body, then parse it.

What node-fetch does—and what it does not

node-fetch brings a Fetch-style API to Node.js. It makes an HTTP request and gives your program a response with methods such as text() and json(). It is not an HTML parser, so it does not provide CSS selectors for finding elements in a page. Use Cheerio or another parser for that step.

A static-page scraper therefore has three distinct jobs:

  1. Fetch: request an absolute URL and receive the response.
  2. Validate: decide whether the response status is acceptable before treating its body as the page you wanted.
  3. Parse: pass the HTML text to a parser and extract the fields you need.

That division matters when something goes wrong: a network failure, an HTTP error page, malformed markup, and content rendered later by JavaScript are different problems and need different fixes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Check Node.js and choose the module format

Using node-fetch v3 with ESM

Version 3 of node-fetch is ESM-only: import it with import, not require(). The maintainers specify Node.js 12.20.0 or later for v3. Install the packages with:

npm install node-fetch cheerio

Set "type": "module" in your project’s package.json, or save the script with the .mjs extension, so Node treats it as an ES module. Current Cheerio documentation states Node.js 22.19 or later; when using a current Cheerio release, meet that stricter runtime requirement and check the requirements of the exact release you install.

Using CommonJS

If the surrounding application uses require(), the simplest compatibility option is node-fetch v2. Alternatively, use dynamic import() from CommonJS to load v3. Do not copy a v3 require('node-fetch') example: it will fail because v3 is ESM-only.

Fetch a page, check its status, and extract fields

This complete ESM example requests a page, limits redirects and response size, cancels a slow request, checks the status, and uses Cheerio to read the title and links. Change the URL and selectors to match a site whose pages you are permitted to access.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
import fetch from 'node-fetch';
import * as cheerio from 'cheerio';

const url = 'https://example.com/';
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 20_000);

try {
  const response = await fetch(url, {
    method: 'GET',
    redirect: 'follow',
    follow: 10,
    size: 2_000_000,
    signal: controller.signal,
    headers: {
      'user-agent': 'ExampleResearchBot/1.0 (contact: dev@example.com)',
      'accept': 'text/html,application/xhtml+xml'
    }
  });

  if (!response.ok) {
    throw new Error(`HTTP ${response.status} ${response.statusText} for ${url}`);
  }

  const contentType = response.headers.get('content-type') ?? '';
  if (!contentType.includes('text/html')) {
    throw new Error(`Expected HTML but received ${contentType || 'an unspecified content type'}`);
  }

  const html = await response.text();
  const $ = cheerio.load(html);
  const title = $('title').first().text().trim();
  const links = $('a[href]').map((_, element) => ({
    text: $(element).text().trim(),
    href: new URL($(element).attr('href'), url).href
  })).get();

  console.log({ title, links });
} catch (error) {
  if (error.name === 'AbortError') {
    console.error(`Request timed out: ${url}`);
  } else {
    console.error(error);
  }
  process.exitCode = 1;
} finally {
  clearTimeout(timer);
}

The user-agent value is an example identity, not a credential or permission to scrape. Replace it with an accurate identifier for your application and a contact route you actually monitor. The two-megabyte size limit is an example bound; choose a limit suitable for the pages your job is expected to receive.

Handle responses and extract data safely

HTTP errors do not automatically enter catch

A frequent source of incorrect scrapers is assuming that a 404 or 500 will throw. node-fetch resolves with a response object for 3xx–5xx statuses; those statuses are not fetch exceptions. Check response.ok or explicitly allow the status codes your task accepts before parsing the body. A response can be successfully received at the network level and still represent a failed page request.

If an error response contains a useful diagnostic body, read it deliberately for logging, but avoid treating it as the requested page’s normal content. Do not attempt to consume the same response body twice: read it once and retain the resulting text if you need both parsing and diagnostics.

Use selectors that match the delivered HTML

Cheerio’s jQuery-like interface can traverse and manipulate parsed HTML. Start with stable selectors such as an element ID, a semantic attribute, or a site’s consistent class. For example, $('h1').first().text().trim() returns the first heading’s text. A selector that matches nothing usually means the markup differs from your assumption, the site returned an error or consent page, or the desired content was never present in the HTTP response.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Resolve relative links against the page URL with the platform’s URL class, as in the example. Otherwise, a value such as /products/1 remains a relative path rather than a usable absolute URL.

Bound the request and body

Use an AbortSignal to cancel a request that takes too long. The non-standard node-fetch v2 timeout option was removed in v3; do not depend on it when writing v3 code. Set size when unexpectedly large responses could consume excessive memory. Decide on redirect behavior intentionally: node-fetch supports follow, manual, and error, and a follow limit helps prevent an unbounded redirect chain.

Cookies, JavaScript pages, and other boundaries

Cookies and sessions

node-fetch does not store cookies by default. If a permitted workflow needs a session, you must handle the cookie flow explicitly—extracting and forwarding cookie headers—or use a cookie-jar solution. A successful request without the expected session may return a sign-in page, a consent prompt, or a reduced version of the content. Do not assume that one request automatically carries state into the next.

JavaScript-rendered content

node-fetch downloads the HTTP response; it does not run the page in a browser’s JavaScript environment. If the HTML response lacks data that appears only after client-side scripts run, inspect whether the site exposes a suitable documented API or use browser automation where appropriate. A parser cannot extract content that was never in the response it received.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Input URLs and server-side request forgery

If your scraper accepts URLs from users or another untrusted source, validate the scheme and permitted hosts before fetching. A server that fetches arbitrary supplied addresses can be abused to make requests to internal services. Cheerio’s loading guidance also calls attention to security considerations when loading from a URL; keep fetching and parsing under your application’s control rather than treating untrusted input as safe.

Be deliberate about load, terms, and reliability

A working HTTP request does not establish that a site permits automated collection. Review the site’s terms and robots guidance, identify your client honestly, throttle requests, cache results where practical, and avoid concurrency that creates unnecessary load. These are operational and compliance decisions for your project; the fact that node-fetch can request a URL does not grant permission to collect its contents.

For a recurring job, record the requested URL, status, content type, elapsed time, and a concise error category. Retry only failures that may be transient, with a bounded retry policy and delay; repeatedly retrying a permanent 403, a malformed URL, or a selector mismatch wastes resources and adds load. The package’s response and error handling gives you the raw signals, but your application must decide what counts as a retryable failure.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common failures

  • ERR_REQUIRE_ESM or an import error: confirm that node-fetch v3 is loaded from ESM. Use import with "type": "module" or .mjs, use dynamic import from CommonJS, or choose v2 if the project must use require().
  • A 404 or 500 is being parsed as a valid page: check response.ok or a deliberate status allow-list before parsing. Those HTTP statuses resolve as responses rather than automatically throwing.
  • The script hangs on a slow site: pass an AbortSignal and set an application-appropriate cancellation period. In v3, the removed timeout option is not the solution.
  • The process uses too much memory: set a reasonable node-fetch size limit, and avoid retaining large response strings longer than needed.
  • The selector returns an empty string: inspect the actual response HTML and content type. Confirm you did not receive an error, login, or consent page, and check whether the content is injected by JavaScript after load.
  • The second request loses the session: cookies are not stored by default. Implement permitted cookie forwarding or use an appropriate cookie-jar solution.
  • Redirects produce the wrong destination or too many hops: choose follow, manual, or error according to the job, and set a finite follow limit.
  • The parser will not install or run: compare your Node.js version with the exact Cheerio release requirement. Current Cheerio documentation states Node.js 22.19 or later, which is stricter than node-fetch v3’s documented minimum.

Or skip the browser setup

If what you need is a screenshot or PDF rather than structured text extracted from HTML, ScreenshotNeo is a website screenshot API and MCP server for developers. A single GET request can return an image or PDF; it is not a replacement for a scraper that needs to select and store page fields. See the ScreenshotNeo site and API documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

ScreenshotNeo accepts cookie or consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.

FAQ

Can node-fetch scrape any website?

It can make HTTP requests, but availability, response content, and permission vary by site. Access controls, terms, session requirements, and JavaScript rendering can all change what a request returns and whether collection is appropriate.

Should I use node-fetch or a browser automation tool?

Use node-fetch when the needed information is present in the HTTP response and you want to parse that response. Consider browser automation when the workflow genuinely depends on browser execution or interaction, while accounting for the extra runtime and the site’s rules.

Can Cheerio fetch a page by itself?

Cheerio parses and traverses HTML; in this workflow, node-fetch performs the HTTP request and supplies the response text. Keeping those responsibilities separate makes status, cancellation, and response handling explicit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.