CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-node-fetch

A light-weight module that brings Fetch API to Node.js

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

http-client.mddocs/

HTTP Client Operations

Core fetch functionality for making HTTP requests with full Web Standards compatibility plus Node.js-specific enhancements like compression, redirect control, and HTTP agent configuration.

Capabilities

fetch Function

The main HTTP client function that performs network requests and returns a Promise resolving to a Response object.

/**
 * Perform an HTTP(S) fetch request
 * @param url - URL string, URL object, or Request instance
 * @param options - Request configuration options
 * @returns Promise resolving to Response object
 */
function fetch(url: string | URL | Request, options?: RequestInit): Promise<Response>;

Basic Usage:

import fetch from 'node-fetch';

// GET request
const response = await fetch('https://api.github.com/users/octocat');
const userData = await response.json();

// POST request
const postResponse = await fetch('https://httpbin.org/post', {
  method: 'POST',
  body: 'Hello World',
  headers: { 'Content-Type': 'text/plain' }
});

Request Configuration

The RequestInit interface provides comprehensive configuration options for HTTP requests.

interface RequestInit {
  // Standard Fetch API options
  method?: string;
  headers?: HeadersInit;
  body?: BodyInit | null;
  redirect?: 'follow' | 'error' | 'manual';
  signal?: AbortSignal | null;
  referrer?: string;
  referrerPolicy?: ReferrerPolicy;
  
  // Node.js specific extensions
  agent?: http.Agent | ((parsedUrl: URL) => http.Agent);
  compress?: boolean;
  follow?: number;
  size?: number;
  highWaterMark?: number;
  insecureHTTPParser?: boolean;
}

Usage Examples:

// Request with custom headers and JSON body
const response = await fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token123'
  },
  body: JSON.stringify({ name: 'John', age: 30 })
});

// Request with custom HTTP agent
import https from 'https';

const agent = new https.Agent({
  keepAlive: true,
  timeout: 30000
});

const response = await fetch('https://api.example.com/data', {
  agent: agent
});

HTTP Methods

Support for all standard HTTP methods through the method option.

type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'PATCH';

Usage Examples:

// Different HTTP methods
const getResponse = await fetch('https://api.example.com/users');

const postResponse = await fetch('https://api.example.com/users', {
  method: 'POST',
  body: JSON.stringify({ name: 'Alice' }),
  headers: { 'Content-Type': 'application/json' }
});

const putResponse = await fetch('https://api.example.com/users/123', {
  method: 'PUT',
  body: JSON.stringify({ name: 'Alice Updated' }),
  headers: { 'Content-Type': 'application/json' }
});

const deleteResponse = await fetch('https://api.example.com/users/123', {
  method: 'DELETE'
});

Request Body Types

Support for various body types including strings, buffers, streams, and form data.

type BodyInit = Blob | Buffer | URLSearchParams | FormData | ReadableStream | string;

Usage Examples:

// String body
await fetch('https://httpbin.org/post', {
  method: 'POST',
  body: 'Plain text content'
});

// JSON body
await fetch('https://httpbin.org/post', {
  method: 'POST',
  body: JSON.stringify({ key: 'value' }),
  headers: { 'Content-Type': 'application/json' }
});

// Form data body
const formData = new FormData();
formData.append('field1', 'value1');
formData.append('field2', 'value2');

await fetch('https://httpbin.org/post', {
  method: 'POST',
  body: formData
});

// Stream body
import { createReadStream } from 'fs';

await fetch('https://httpbin.org/post', {
  method: 'POST',
  body: createReadStream('./file.txt'),
  headers: { 'Content-Type': 'text/plain' }
});

Redirect Handling

Control how redirects are handled during requests.

type RedirectMode = 'follow' | 'error' | 'manual';

Usage Examples:

// Follow redirects automatically (default)
const response = await fetch('https://github.com/node-fetch/node-fetch', {
  redirect: 'follow'
});

// Throw error on redirect
try {
  await fetch('https://github.com/node-fetch/node-fetch', {
    redirect: 'error'
  });
} catch (error) {
  console.log('Redirect encountered:', error.message);
}

// Handle redirects manually
const response = await fetch('https://github.com/node-fetch/node-fetch', {
  redirect: 'manual'
});

if (response.status >= 300 && response.status < 400) {
  const location = response.headers.get('location');
  console.log('Redirect to:', location);
}

Request Timeout and Cancellation

Use AbortSignal to cancel requests or implement timeouts.

interface AbortSignal {
  readonly aborted: boolean;
  addEventListener(type: 'abort', listener: () => void): void;
  removeEventListener(type: 'abort', listener: () => void): void;
}

Usage Examples:

// Request cancellation with AbortController
const controller = new AbortController();
const signal = controller.signal;

// Cancel request after 5 seconds
setTimeout(() => controller.abort(), 5000);

try {
  const response = await fetch('https://api.example.com/slow-endpoint', {
    signal: signal
  });
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('Request was cancelled');
  }
}

// Request timeout helper
function fetchWithTimeout(url, options = {}, timeout = 5000) {
  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeout);
  
  return fetch(url, {
    ...options,
    signal: controller.signal
  }).finally(() => clearTimeout(id));
}

Node.js Specific Options

Advanced configuration options specific to Node.js environments.

interface NodeRequestOptions {
  agent?: http.Agent | ((parsedUrl: URL) => http.Agent);
  compress?: boolean;
  follow?: number;
  size?: number;
  highWaterMark?: number;
  insecureHTTPParser?: boolean;
}

Usage Examples:

// Custom compression settings
const response = await fetch('https://api.example.com/large-data', {
  compress: false  // Disable automatic decompression
});

// Custom redirect limit
const response = await fetch('https://example.com/redirect-chain', {
  follow: 5  // Follow maximum 5 redirects
});

// Response size limit
const response = await fetch('https://api.example.com/large-file', {
  size: 1024 * 1024  // Limit response to 1MB
});

// Custom stream buffer size
const response = await fetch('https://api.example.com/stream', {
  highWaterMark: 64 * 1024  // 64KB buffer
});

Default Headers

Headers automatically added by node-fetch when not explicitly provided.

interface DefaultHeaders {
  'Accept-Encoding': 'gzip, deflate, br';  // When compress: true
  'Accept': '*/*';
  'Content-Length': string;  // Calculated automatically
  'Host': string;  // From target URL
  'Transfer-Encoding': 'chunked';  // When body is stream
  'User-Agent': 'node-fetch';
}

Override defaults:

const response = await fetch('https://api.example.com/data', {
  headers: {
    'User-Agent': 'MyApp/1.0',
    'Accept': 'application/json'
  }
});

docs

body-processing.md

error-handling.md

file-blob.md

headers.md

http-client.md

index.md

request-response.md

utilities.md

tile.json