r2 HTTP Client

raw JSON →
2.0.1 verified Thu Apr 23 auth: no javascript abandoned

The `r2` package is a minimalist, promise-based HTTP client library envisioned as a spiritual successor to the popular `request` package. It distinguishes itself by being built primarily upon the browser's Fetch API, with Node.js support provided through shims, resulting in a substantially smaller footprint, particularly for browser environments (e.g., 66KB uncompressed for `r2` versus 2MB for `request` when bundled). The library's API is designed for modern JavaScript development, leveraging `async/await` for asynchronous operations. The current stable version is 2.0.1, released in April 2018. Its release cadence has been effectively halted since then, indicating long-term dormancy. A primary differentiator is its Fetch API-first design, aiming for simplicity and efficiency over feature-rich complexity, making it a lightweight option for basic HTTP interactions.

error SyntaxError: await is only valid in async functions and the top level bodies of modules
cause Attempting to use `await` keyword outside of an `async` function or a module explicitly configured as an ES module.
fix
Wrap the code using await in an async function and call it. Example: async function myFunc() { await r2(...); } myFunc();.
error TypeError: r2 is not a function
cause Attempting to instantiate r2 using `new r2()`, or calling a method on an undefined `r2` variable.
fix
r2 is a function that returns a promise-like object directly, not a class. Call it as await r2('url').text. Ensure const r2 = require('r2') is correctly defined and in scope.
error Error: getaddrinfo ENOTFOUND localhost
cause The hostname specified in the URL (e.g., 'localhost') could not be resolved by the DNS system, or the network connection is unavailable.
fix
Verify the URL is correct and the target server is running and accessible from your environment. For 'localhost', ensure the server is listening on the correct port and address.
breaking Version 2.0.0 introduced a complete overhaul of the API, explicitly stating "MAJOR API BREAK OF EVERY METHOD AND THE HASHER." Code written for v1.x will not be compatible with v2.x without significant refactoring.
fix Consult the v2.0.0 source code or documentation (if available) to understand the new API surface, as explicit migration guides are scarce.
gotcha The `r2` package has not received updates since April 2018. This means it may contain unpatched security vulnerabilities, outdated dependencies, or compatibility issues with newer Node.js versions or browser environments.
fix Evaluate alternatives like `node-fetch`, `axios`, or the native `fetch` API (with a polyfill for Node.js) for projects requiring active maintenance, security updates, and modern features. Use `r2` with caution in production, especially for new projects.
gotcha `r2` is built on the Fetch API but is primarily a CommonJS module. It does not natively support ES Modules (import/export syntax) without a transpilation step (e.g., Babel, TypeScript) or a wrapper.
fix Use `const r2 = require("r2")` for Node.js environments. For browser environments where ES Modules are preferred, consider bundling with tools like Webpack or Rollup, or use a modern HTTP client with native ESM support.
npm install r2
yarn add r2
pnpm add r2

Demonstrates basic GET requests for text, PUT requests with JSON payloads, and GET requests with custom headers using r2's async/await interface.

const r2 = require('r2');

async function fetchData() {
  try {
    // Fetch HTML content from Google
    const html = await r2('https://www.google.com').text;
    console.log('Google HTML (truncated):', html.substring(0, 100) + '...');

    // Send a PUT request with JSON data and receive JSON response
    const payload = { status: 'success', timestamp: Date.now() };
    const jsonResponse = await r2.put('https://httpbin.org/put', { json: payload }).json;
    console.log('HTTPBin PUT response:', jsonResponse);

    // Fetch with custom headers
    const headers = { 'x-custom-header': 'r2-test' };
    const responseWithHeaders = await r2('https://httpbin.org/headers', { headers }).json;
    console.log('HTTPBin Headers response:', responseWithHeaders.headers['X-Custom-Header']);

  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

fetchData();