Home
Curl To Fetch

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.

Raw cURL Command(388 chars)
Parsed Breakdown
POST
https://api.github.com/repos/octocat/Hello-World/issues
Auth Mode
bearer
Payload Format
json
Headers Count
4 Custom
Timeout
Default
// 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();
Syntax Ready40 Lines:
Integration Quick Notes
  • •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 FlagCategoryDescriptionFetch Equivalent
-X(--request)GeneralSpecifies custom request method (POST, PUT, DELETE, PATCH, etc.)method: 'POST'
-H(--header)HeadersExtra HTTP header to include in requestheaders: { 'Header': 'value' }
-d(--data)BodyHTTP POST data payload (JSON, urlencoded string, or raw text)body: JSON.stringify(...) or body: '...'
--json(--json)BodySends 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)BodySends raw data payload without @ special character handlingbody: '...'
--data-urlencode(--data-urlencode)BodyURL-encodes data payload parametersbody: new URLSearchParams(...)
-F(--form)BodyMultipart form data (mimics browser form submission / file upload)const form = new FormData()
-u(--user)AuthHTTP Basic Authentication username:password credentialsheaders: { 'Authorization': 'Basic ' + btoa('user:pass') }
--oauth2-bearer(--oauth2-bearer)AuthOAuth 2.0 Bearer access tokenheaders: { 'Authorization': 'Bearer ' + token }
-A(--user-agent)HeadersCustom User-Agent string headerheaders: { 'User-Agent': '...' }
-b(--cookie)HeadersCookie header or cookie jar stringcredentials: 'include' (Browser) or headers: { Cookie: '...' }
-e(--referer)HeadersReferer URL headerheaders: { 'Referer': '...' }
-m(--max-time)NetworkMaximum time in seconds allowed for the transfersignal: AbortSignal.timeout(ms)
-L(--location)NetworkFollow HTTP 3xx redirects automaticallyredirect: 'follow'
-I(--head)GeneralFetch the HTTP header only (HEAD request method)method: 'HEAD'
-k(--insecure)NetworkAllow insecure SSL/TLS certificate connectionsagent: new https.Agent({ rejectUnauthorized: false }) (Node)
--compressed(--compressed)NetworkRequest compressed response (gzip, deflate, brotli)Handled natively by browser / modern runtime
-G(--get)GeneralAppend -d data parameters into the URL query stringAppends 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.

Technical Reference & Architecture Guide

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.

cURL to JavaScript Fetch & Axios Converter Cheatsheet — Client-Side In-Memory Architecture & Data Flow
cURL to JavaScript Fetch & Axios Converter Cheatsheet — Client-Side In-Memory Architecture & Data Flow

Key Parameters & Controls

Key Parameters & Controls
ParameterType / UnitDescriptionDefault
rawCurlstringRaw cURL command line string copied from terminal, Postman, or browser network tab.Auto
wrapInFunctionbooleanWraps the generated request in an async JavaScript function or arrow routine.true
checkResponseOkbooleanAdds explicit response.ok inspection to reject HTTP 4xx and 5xx response statuses.true
formatJsonAsObjectbooleanParses JSON string bodies into clean inline JavaScript object literals.true

Pro Tips & Best Practices

Bypass Browser CORS Constraints

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.

Inspect response.ok for 4xx/5xx Errors

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

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.