Back to Blog

How to Convert cURL Command to JavaScript Fetch

Complete Guide to Converting cURL to Fetch API (2026)

Definition: What is cURL to Fetch Conversion?

Converting cURL to JavaScript fetch is the process of translating a cURL command-line HTTP request into equivalent JavaScript code using the Fetch API. cURL is a command-line tool for making HTTP requests, while fetch is a JavaScript API that provides similar functionality in web browsers and Node.js environments.

cURL commands use flags like -X for HTTP methods, -H for headers, -d for data, and -u for authentication. The Fetch API uses an options object with properties like method, headers, body, and credentials to achieve the same results.

Converting cURL to fetch is useful when you have a working cURL command (perhaps from API documentation or testing) and need to implement the same request in a JavaScript application. Understanding the mapping between cURL flags and fetch options is essential for accurate conversion.

Key Point: cURL and fetch both make HTTP requests but use different syntax. Converting cURL to fetch involves mapping cURL flags to fetch options: -X becomes method, -H becomes headers, -d becomes body, and -u becomes Authorization header.

What: Understanding cURL and Fetch API

cURL and Fetch API comparison:

cURL Command Structure

cURL commands use flags: -X for method, -H for headers, -d for data, -u for authentication, --data-raw for raw data. The URL comes first, followed by flags.

Example: curl -X POST https://api.example.com -H "Header: Value" -d 'data'

Fetch API Structure

Fetch API uses fetch(url, options) where options is an object with method, headers, body, credentials, and other properties. Headers are an object, body is a string or FormData.

Example: fetch(url, with method, headers, and body options)

Common Conversions

Common mappings: -X GET becomes method: "GET", -H "Key: Value" becomes headers object with Key: Value, -d 'data' becomes body: "data", -u user:pass becomes headers with Authorization: Basic.

Understanding these mappings enables accurate conversion.

Response Handling

cURL outputs response directly, while fetch returns a Promise that resolves to a Response object. You need to call .json(), .text(), or .blob() to extract data from the response.

Fetch requires explicit response parsing.

Important: cURL and fetch make the same HTTP requests but use different syntax. Understanding the mapping between cURL flags and fetch options is essential for accurate conversion. Always test converted fetch requests to ensure they work correctly.

When: When to Convert cURL to Fetch

You should convert cURL to fetch in these situations:

API Documentation Examples

When API documentation provides cURL examples, you need to convert them to fetch for use in JavaScript applications. This is common when integrating third-party APIs or services.

Testing and Development

When you've tested an API request with cURL and it works, converting it to fetch allows you to implement the same request in your JavaScript application. This ensures consistency between testing and implementation.

Browser-Based Applications

When building web applications that need to make HTTP requests from the browser, you must use fetch (or XMLHttpRequest) since cURL is a command-line tool. Converting cURL to fetch enables browser-based API calls.

Node.js Applications

When building Node.js applications, you can use fetch (Node.js 18+) or need to convert cURL commands to fetch for consistency with browser code. Fetch provides a modern, Promise-based API for HTTP requests.

Common Scenario: Converting cURL to fetch is most common when implementing API integrations in JavaScript applications. API documentation often provides cURL examples, which need to be converted to fetch for use in web or Node.js applications.

How To: Step-by-Step Conversion Guide

Follow these steps to convert cURL commands to JavaScript fetch:

Method 1: Basic GET Request

Simple GET Request

Convert a basic GET request:

// cURL
curl https://api.example.com/users

// JavaScript Fetch
fetch('https://api.example.com/users')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

// Or with async/await
async function getUsers() {
  try {
    const response = await fetch('https://api.example.com/users');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error:', error);
  }
}

Method 2: GET Request with Headers

Headers Conversion

Convert cURL headers to fetch headers:

// cURL
curl -H "Authorization: Bearer token123" \
     -H "Content-Type: application/json" \
     https://api.example.com/users

// JavaScript Fetch
fetch('https://api.example.com/users', {
  headers: {
    'Authorization': 'Bearer token123',
    'Content-Type': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Method 3: POST Request with JSON Data

POST with JSON Body

Convert POST request with JSON data:

// cURL
curl -X POST https://api.example.com/users \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer token123" \
     -d '{"name": "John", "email": "john@example.com"}'

// JavaScript Fetch
fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token123'
  },
  body: JSON.stringify({
    name: 'John',
    email: 'john@example.com'
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Method 4: PUT and DELETE Requests

PUT and DELETE Methods

Convert PUT and DELETE requests:

// cURL PUT
curl -X PUT https://api.example.com/users/123 \
     -H "Content-Type: application/json" \
     -d '{"name": "Jane"}'

// JavaScript Fetch PUT
fetch('https://api.example.com/users/123', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Jane'
  })
})
  .then(response => response.json())
  .then(data => console.log(data));

// cURL DELETE
curl -X DELETE https://api.example.com/users/123 \
     -H "Authorization: Bearer token123"

// JavaScript Fetch DELETE
fetch('https://api.example.com/users/123', {
  method: 'DELETE',
  headers: {
    'Authorization': 'Bearer token123'
  }
})
  .then(response => response.json())
  .then(data => console.log(data));

Method 5: Authentication (Bearer Token, Basic Auth)

Bearer Token Authentication

Convert Bearer token authentication:

// cURL with Bearer token
curl -H "Authorization: Bearer your-token-here" \
     https://api.example.com/protected

// JavaScript Fetch with Bearer token
fetch('https://api.example.com/protected', {
  headers: {
    'Authorization': 'Bearer your-token-here'
  }
})
  .then(response => response.json())
  .then(data => console.log(data));

Basic Authentication

Convert Basic authentication:

// cURL with Basic auth
curl -u username:password https://api.example.com/protected

// JavaScript Fetch with Basic auth
const credentials = btoa('username:password');
fetch('https://api.example.com/protected', {
  headers: {
    'Authorization': 'Basic ' + credentials
  }
})
  .then(response => response.json())
  .then(data => console.log(data));

Method 6: Form Data and File Uploads

Form Data

Convert form data requests:

// cURL with form data
curl -X POST https://api.example.com/upload \
     -F "name=John" \
     -F "email=john@example.com" \
     -F "file=@/path/to/file.jpg"

// JavaScript Fetch with FormData
const formData = new FormData();
formData.append('name', 'John');
formData.append('email', 'john@example.com');
formData.append('file', fileInput.files[0]); // File from input

fetch('https://api.example.com/upload', {
  method: 'POST',
  body: formData
  // Note: Don't set Content-Type header, browser sets it automatically
})
  .then(response => response.json())
  .then(data => console.log(data));

Method 7: Query Parameters

URL Query Strings

Handle query parameters:

// cURL with query parameters
curl "https://api.example.com/search?q=javascript&limit=10"

// JavaScript Fetch with query parameters
const params = new URLSearchParams({
  q: 'javascript',
  limit: '10'
});

fetch('https://api.example.com/search?' + params)
  .then(response => response.json())
  .then(data => console.log(data));

// Or manually construct URL
const url = new URL('https://api.example.com/search');
url.searchParams.append('q', 'javascript');
url.searchParams.append('limit', '10');

fetch(url.toString())
  .then(response => response.json())
  .then(data => console.log(data));

Best Practice: Always test converted fetch requests to ensure they work correctly. Pay attention to Content-Type headers, especially for JSON (application/json) and form data (multipart/form-data). Use async/await for cleaner code, and handle errors appropriately.

Why: Why Convert cURL to Fetch

Converting cURL to fetch is important for several reasons:

Browser Compatibility

cURL is a command-line tool and cannot run in browsers. Converting cURL to fetch enables HTTP requests in web applications, allowing you to make API calls directly from JavaScript running in browsers.

Modern JavaScript

Fetch API is the modern standard for HTTP requests in JavaScript. It provides a Promise-based API that's more intuitive than XMLHttpRequest and works consistently across modern browsers and Node.js.

API Integration

Many APIs provide cURL examples in their documentation. Converting these to fetch allows you to implement the same requests in your JavaScript applications, ensuring consistency between documentation and implementation.

Development Workflow

Converting cURL to fetch streamlines development workflow. You can test APIs with cURL, then convert working commands to fetch for implementation, reducing errors and ensuring requests work correctly.

Important: Understanding how to convert cURL to fetch is essential for JavaScript developers. It enables you to use API documentation examples, implement API integrations, and make HTTP requests in browser and Node.js applications.

cURL to Fetch Conversion Reference

HTTP Methods

curl -X GET    becomes method: 'GET'
curl -X POST   becomes method: 'POST'
curl -X PUT    becomes method: 'PUT'
curl -X DELETE becomes method: 'DELETE'
curl -X PATCH  becomes method: 'PATCH'

Headers

curl -H "Header: Value" becomes headers object with Header: Value
curl -H "Content-Type: application/json"
     becomes headers object with Content-Type: application/json

Data/Body

curl -d with JSON data becomes body: JSON.stringify(data)
curl -d "key=value"        becomes body: 'key=value' (form data)
curl --data-raw 'data'     becomes body: 'data'

Authentication

curl -H "Authorization: Bearer token"
     becomes headers object with Authorization: Bearer token

curl -u user:pass
     becomes headers object with Authorization: Basic + btoa

Frequently Asked Questions

How do I convert cURL headers to fetch headers?

Convert cURL -H flags to fetch headers object. Each -H "Header: Value" becomes a key-value pair in the headers object. Example: curl -H "Authorization: Bearer token" -H "Content-Type: application/json" becomes fetch(url, with headers object containing Authorization and Content-Type).

How do I convert cURL POST data to fetch body?

Convert cURL -d or --data flags to fetch body. For JSON data, use JSON.stringify(). For form data, use URLSearchParams or FormData. Example: curl -d with JSON data becomes body: JSON.stringify(data) with Content-Type: application/json header.

How do I handle authentication in fetch from cURL?

Convert cURL authentication to fetch headers. For Bearer tokens: curl -H "Authorization: Bearer token" becomes headers with Authorization: Bearer token. For Basic auth: curl -u user:pass becomes headers with Authorization: Basic + btoa. For API keys: curl -H "X-API-Key: key" becomes headers with X-API-Key: key.

What's the difference between cURL and fetch API?

cURL is a command-line tool for making HTTP requests, while fetch is a JavaScript API for making HTTP requests in browsers and Node.js. cURL uses flags like -X, -H, -d, while fetch uses an options object with method, headers, and body properties. Both can make the same HTTP requests, but fetch is used in JavaScript applications.

How do I handle fetch response errors?

Fetch doesn't reject on HTTP error status codes (404, 500, etc.). Check response.ok or response.status to handle errors: if (!response.ok) throw new Error('HTTP error'). Network errors (connection failures) cause fetch to reject the Promise. Always handle both cases with try-catch blocks to check response.ok and handle errors appropriately.

Share this article with Your Friends, Collegue and Team mates

Stay Updated

Get the latest tool updates, new features, and developer tips delivered to your inbox.

No spam. Unsubscribe anytime. We respect your privacy.

Feedback for How to Convert cURL to JavaScript Fetch Guide

Help us improve! Share your thoughts, report bugs, or suggest new features.

Get in Touch

We'd love to hear from you! Write us for any additional feature request, issues, query or appreciation.

Your feedback helps us improve and build better tools for the developer community.