Turning a curl Command Into fetch or axios — What Translates and What Doesn’t

By · Published

A curl command pasted from a bug report or an API doc is a shell command. To turn it into JavaScript you parse its flags and rebuild the equivalent request options object: -X/--request for the method, -H/--header for headers, -d/--data/--data-raw/--data-binary for the body, and -u/--user for basic auth.

curl -X POST https://api.example.com/orders \
  -H "Content-Type: application/json" \
  -d '{"item":"widget","qty":3}'

↓

fetch('https://api.example.com/orders', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: '{"item":"widget","qty":3}',
})

-u/--user becomes a Basic auth header

curl -u user:pass https://... has no direct fetch equivalent, because the Fetch API has no credentials shorthand like curl's. The converter emits what curl itself sends on the wire: an Authorization: Basic <base64(user:pass)> header. One edge case: base64-encoding the credentials in the browser uses btoa, which only handles Latin1 text. A password with non-Latin1 characters won't encode cleanly this way. curl's own -u flag has the same limitation when the terminal encoding doesn't match.

Only one direction is supported, on purpose

Advertisement

Conversion goes curl → fetch/axios and not back. The reverse has no single correct answer. The same fetch call can be written a dozen equivalent ways (destructured options, a helper wrapper, chained .then() vs await), so there's no one grammar to parse JavaScript back into. curl's flag syntax is known and bounded, which makes the forward direction well-defined.

What doesn't translate

--compressed, cookie jars (-b/-c), and multipart form uploads (-F) aren't covered. Each maps to a different amount of code in fetch/axios (a FormData object, a cookie-handling layer) rather than a one-line option, so they're out of scope for a flag-to-option translator. If your command uses one of them, the URL, method, headers, and body still convert, and you add the rest by hand.

Importing a Postman collection works the same way

A Postman v2.x collection export (JSON) goes through the same code path. Each request becomes the same method/URL/headers/body shape a parsed curl command produces, and folders of nested requests get flattened. The gap is bodies: only the raw body mode is read. form-data, urlencoded, and binary bodies can't be represented as a single body string without picking an encoding, so those requests come through with an empty body. Check the original collection for them.

Advertisement

Try the curl → fetch/axios →