Convert Fetch HTTP Requests to cURL

0.6.0 · active · verified Wed Apr 22

fetch-to-curl is a JavaScript/TypeScript utility library that generates `curl` commands from standard Web Fetch API inputs, including URLs, `Request` objects, and `RequestInit` options. Currently at version 0.6.0, it aims for simplicity and minimalism with zero external dependencies. Unlike libraries that patch the global `fetch` object, fetch-to-curl operates as a standalone wrapper, ensuring no side effects on your application's actual network requests. Releases are made periodically to address bug fixes and add minor enhancements, as seen with recent updates supporting URL objects and improving escaping. It is differentiated by its lightweight nature and its direct translation approach, making it ideal for debugging HTTP requests in development environments without modifying the runtime behavior of the application.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates converting `fetch` parameters (URL, options, `Request` object, `URL` object) into a cURL command string for debugging.

import { fetchToCurl } from 'fetch-to-curl';

// Example 1: Basic URL and options
const urlWithOptions = 'https://api.example.com/data';
const options = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.API_TOKEN ?? ''}`
  },
  body: JSON.stringify({ key: 'value', id: 123 }),
};

console.log('--- cURL from URL and options ---');
console.log(fetchToCurl(urlWithOptions, options));

// Example 2: Using a Request object
const requestObject = new Request('https://api.example.com/users', {
  method: 'GET',
  headers: new Headers({
    'Accept': 'application/xml',
    'X-Custom-Header': 'Hello'
  }),
});

console.log('\n--- cURL from Request object ---');
console.log(fetchToCurl(requestObject));

// Example 3: URL object support (since v0.6.0)
const urlObj = new URL('https://example.com/search');
urlObj.searchParams.set('q', 'test');
urlObj.searchParams.set('page', '2');
const optionsWithUrlObj = { method: 'GET' };

console.log('\n--- cURL from URL object ---');
console.log(fetchToCurl(urlObj, optionsWithUrlObj));

view raw JSON →