cURL to JavaScript Fetch & Axios Converter
ES2024 / Axios / Node 18+Convert raw cURL shell commands into idiomatic JavaScript Fetch API, TypeScript, Axios, and Node.js code with instant syntax highlighting and client-side privacy.
// JavaScript Native Fetch (async/await)
async function sendRequest() {
const url = "https://api.github.com/repos/octocat/Hello-World/issues";
const headers = {
Accept: "application/vnd.github+json",
Authorization: "Bearer gho_16C7e42F292c6912E7710c838347Ae178B4a",
"X-GitHub-Api-Version": "2022-11-28",
"Content-Type": "application/json"
};
const body = JSON.stringify({
"title": "Found a bug in auth flow",
"body": "Need to inspect JWT claims properly",
"labels": [
"bug",
"critical"
]
});
try {
const response = await fetch(url, {
method: "POST",
headers,
body
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Response:', data);
return data;
} catch (error) {
console.error('Request failed:', error);
}
}
sendRequest();- •CORS Restrictions: Browser Fetch enforces Same-Origin Policy. If you get a CORS error, dispatch your request via a Next.js Route Handler (/api/...) or backend proxy.
- •FormData Boundaries: When uploading with new FormData(), do not set Content-Type manually; the browser calculates the multipart boundary automatically.
- •AbortSignal Timeout: Modern runtimes support AbortSignal.timeout(ms) for elegant timeout management without manual setTimeout listeners.
cURL to Fetch Flag Reference
Common cURL command line options and their JavaScript Fetch translation mapping.
| cURL Flag | Category | Description | Fetch Equivalent |
|---|---|---|---|
| -X(--request) | General | Specifies custom request method (POST, PUT, DELETE, PATCH, etc.) | method: 'POST' |
| -H(--header) | Headers | Extra HTTP header to include in request | headers: { 'Header': 'value' } |
| -d(--data) | Body | HTTP POST data payload (JSON, urlencoded string, or raw text) | body: JSON.stringify(...) or body: '...' |
| --json(--json) | Body | Sends JSON data and sets Content-Type/Accept to application/json (curl 7.82+) | headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(...) |
| --data-raw(--data-raw) | Body | Sends raw data payload without @ special character handling | body: '...' |
| --data-urlencode(--data-urlencode) | Body | URL-encodes data payload parameters | body: new URLSearchParams(...) |
| -F(--form) | Body | Multipart form data (mimics browser form submission / file upload) | const form = new FormData() |
| -u(--user) | Auth | HTTP Basic Authentication username:password credentials | headers: { 'Authorization': 'Basic ' + btoa('user:pass') } |
| --oauth2-bearer(--oauth2-bearer) | Auth | OAuth 2.0 Bearer access token | headers: { 'Authorization': 'Bearer ' + token } |
| -A(--user-agent) | Headers | Custom User-Agent string header | headers: { 'User-Agent': '...' } |
| -b(--cookie) | Headers | Cookie header or cookie jar string | credentials: 'include' (Browser) or headers: { Cookie: '...' } |
| -e(--referer) | Headers | Referer URL header | headers: { 'Referer': '...' } |
| -m(--max-time) | Network | Maximum time in seconds allowed for the transfer | signal: AbortSignal.timeout(ms) |
| -L(--location) | Network | Follow HTTP 3xx redirects automatically | redirect: 'follow' |
| -I(--head) | General | Fetch the HTTP header only (HEAD request method) | method: 'HEAD' |
| -k(--insecure) | Network | Allow insecure SSL/TLS certificate connections | agent: new https.Agent({ rejectUnauthorized: false }) (Node) |
| --compressed(--compressed) | Network | Request compressed response (gzip, deflate, brotli) | Handled natively by browser / modern runtime |
| -G(--get) | General | Append -d data parameters into the URL query string | Appends params to URLSearchParams |
Native Fetch vs. Axios Comparison
Native Fetch API
Zero Dependencies- Zero Bundle Cost: Built directly into all modern web browsers and Node.js 18+.
- Standards Compliant: Official W3C WHATWG specification, universal web standard.
- Manual JSON Parsing: Requires calling await response.json() explicitly.
- HTTP Error Statuses: Does NOT reject on 404 or 500 status codes; must inspect response.ok.
Axios Library
Feature Rich- Automatic JSON Transformation: Access parsed data directly via response.data.
- Automatic Error Rejection: Status codes outside 2xx automatically trigger the catch block.
- Interceptors & Auth: Built-in support for request/response middleware and native auth configs.
- External Package: Requires npm install axios and adds ~13KB to client bundle.
Zero-Knowledge Local Execution
All data processing, parsing, and compilation execute strictly inside your local browser memory. Zero external server uploads.
Instant Client-Side Engine
Instant real-time reactive computation delivers immediate feedback on every keystroke with zero network latency.
Production Standards & Compliance
Strictly validates syntax, edge cases, and formatting rules for dependable production output.
cURL to JavaScript Fetch & Axios Converter Cheatsheet
Convert raw cURL shell commands into idiomatic JavaScript Fetch API, TypeScript, Axios, and Node.js code with instant syntax highlighting and client-side privacy.
Key Parameters & Controls
| Parameter | Type / Unit | Description | Default |
|---|---|---|---|
| rawCurl | string | Raw cURL command line string copied from terminal, Postman, or browser network tab. | Auto |
| wrapInFunction | boolean | Wraps the generated request in an async JavaScript function or arrow routine. | true |
| checkResponseOk | boolean | Adds explicit response.ok inspection to reject HTTP 4xx and 5xx response statuses. | true |
| formatJsonAsObject | boolean | Parses JSON string bodies into clean inline JavaScript object literals. | true |
Pro Tips & Best Practices
cURL executes outside the browser sandbox without CORS checks. If Fetch throws 'Access-Control-Allow-Origin' errors, dispatch the request from a backend Route Handler or serverless function.
Unlike Axios, native Fetch only rejects network failures (DNS/offline). It resolves successfully on 404 or 500 status codes. Always verify response.ok before parsing JSON.
Set client-side timeout bounds by passing signal: AbortSignal.timeout(5000) to fetch, protecting user interfaces from indefinite hangs.
Common Gotchas & Troubleshooting
⚠️Fetch throws 'TypeError: Failed to fetch' immediately in browser
Check your browser DevTools Console for Cross-Origin Resource Sharing (CORS) blocks or mixed-content SSL protocol mismatches (HTTP vs HTTPS).
⚠️JSON payload sends escaped string instead of object
Enable the 'Format JSON body as object' option in settings or ensure JSON.stringify(payload) matches your Content-Type header.
Frequently Asked Questions
How does cURL Basic Auth (-u user:pass) translate to JavaScript Fetch?▼
cURL credentials convert into an Authorization: Basic <base64> header. In JavaScript, this is constructed using 'Basic ' + btoa('user:pass'). In Node.js, Buffer.from('user:pass').toString('base64') is utilized.
Why does native Fetch require calling await response.json() explicitly?▼
Fetch streams response bodies as ReadableStream chunks. Calling response.json() or response.text() asynchronously drains and parses the body buffer without blocking the event loop.
Can I convert complex multi-line cURL commands with backslashes?▼
Yes. Our client-side lexer normalizes POSIX backslashes (\), Windows cmd carats (^), and PowerShell backticks (`), accurately preserving quoted arguments and line breaks.
Is my cURL command or auth secret sent to any remote server?▼
Never. 100% of the token parsing and code generation executes strictly inside your browser sandbox. No server-side telemetry or logging is involved.
Related Tools & Utilities
All Tools →Parse, analyze, and convert raw curl commands into JSON request objects, Fetch API, Axios requests, and Python code snippets in your browser.
Convert cURL shell commands into idiomatic Golang net/http client requests with headers, cookies, and JSON payloads.
Convert command-line cURL syntax into robust PHP code using native curl_init, GuzzleHttp client, Laravel Http facade, or WordPress API.
Translate command-line cURL requests into idiomatic C# code using .NET HttpClient, RestSharp, or Flurl.Http.
Paste any raw cURL command from Chrome DevTools and generate idiomatic Python code using `requests` or async `httpx`.
Generate zero-dependency native fetch TypeScript API methods with query string serialization, headers, and response types.