root/learning-hub/api-automation/convert-curl-to-fetch-axios
← Back to Learning Hub
API & AUTOMATION6 min readBeginner100% Client-Side Verified

Convert cURL to JavaScript — Fetch, Axios & Node.js Guide with Code

Learn how to convert any cURL command to native JavaScript fetch() and Axios. Covers headers, JSON bodies, bearer auth, query parameters, and error handling.

#JavaScript#TypeScript#cURL#Fetch#Axios#Node.js

Interactive cURL to Fetch Converter

Live Interactive Sandbox
100% Client-Side

Converts bash cURL with custom headers and POST payload into modern ES2024 fetch. Test the preset input below or customize it before launching into the full workspace.

cURL Command:
Ready for advanced parsing, syntax error highlighting & bulk export?
Open in Full Workspace (cURL to Fetch)

When inspecting network traffic in Chrome DevTools or reading modern API documentation (Stripe, GitHub, OpenAI), code samples are universally provided as curl commands.

When writing modern client-side React code or backend Node.js microservices, translating those commands into clean fetch() or axios calls is a daily developer task.

This guide provides a complete flag-by-flag mapping.


1. The Core cURL to Fetch Mapping Table

cURL Flag Native fetch() Option axios Config
-X POST method: 'POST' method: 'post'
-H "Key: Val" headers: { 'Key': 'Val' } headers: { 'Key': 'Val' }
-d '{"k":"v"}' body: JSON.stringify({ k: 'v' }) data: { k: 'v' }
-u user:pass headers: { 'Authorization': 'Basic ...' } auth: { username, password }
--connect-timeout signal: AbortSignal.timeout(5000) timeout: 5000

2. Basic GET Request

cURL:

curl "https://api.example.com/v1/items?limit=10&status=active"

Native Fetch (Modern Async/Await):

const url = new URL('https://api.example.com/v1/items');
url.searchParams.set('limit', '10');
url.searchParams.set('status', 'active');

const response = await fetch(url.toString(), {
  method: 'GET',
});

if (!response.ok) {
  throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();
console.log(data);

Axios:

import axios from 'axios';

const { data } = await axios.get('https://api.example.com/v1/items', {
  params: {
    limit: 10,
    status: 'active',
  },
});
console.log(data);

3. POST Request with JSON Body & Bearer Auth

cURL:

curl -X POST https://api.example.com/v1/orders \
  -H "Authorization: Bearer my_secret_token_123" \
  -H "Content-Type: application/json" \
  -d '{"itemId": "item_987", "quantity": 3}'

Native Fetch:

const response = await fetch('https://api.example.com/v1/orders', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer my_secret_token_123',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    itemId: 'item_987',
    quantity: 3,
  }),
});

if (!response.ok) {
  const errorData = await response.json().catch(() => null);
  throw new Error(errorData?.message || `Request failed with status ${response.status}`);
}

const result = await response.json();
console.log(result);

4. Production Timeout Handling with AbortSignal

In modern JavaScript (Node.js 18+ and all evergreen browsers), never call fetch() without a timeout signal:

try {
  const res = await fetch('https://api.example.com/slow-endpoint', {
    signal: AbortSignal.timeout(4000), // Automatically aborts after 4 seconds
  });
  const data = await res.json();
} catch (err: any) {
  if (err.name === 'TimeoutError') {
    console.error('Request timed out after 4 seconds');
  } else {
    console.error('Network failure:', err);
  }
}

Live Tool: cURL to JavaScript Fetch

Client-Side Engine

Translate bash cURL commands into JavaScript fetch() API calls.

Launch Tool Workspace

Frequently Asked Questions (FAQ)

No! Native fetch() only rejects on network failures. For 400/404/500 responses, fetch resolves successfully. You must check 'if (!response.ok)' manually.