All Tools / Blog / How to Convert a cURL Command to JavaScript fetch()

How to Convert a cURL Command to JavaScript fetch()

2 min read

A cURL command and a JavaScript fetch() call describe the same HTTP request in different syntax. Converting between them is mostly a matter of mapping cURL's flags to fetch's options object. Once you know the mapping, any command translates directly.

The flag mapping

cURL flag fetch equivalent
-X POST method: "POST"
-H "Key: Value" an entry in headers
-d '...' / --data body (and implies POST)
-u user:pass Authorization: Basic … header
-b "name=value" Cookie header

A worked example

This cURL command posts JSON with an auth header:

curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer abc123" \
  -d '{"name":"Ada","role":"admin"}'

Becomes this fetch() call:

fetch("https://api.example.com/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Authorization": "Bearer abc123"
  },
  body: JSON.stringify({ name: "Ada", role: "admin" })
});

Two things to notice: -d with a method makes it a POST, and a JSON string body pairs with a Content-Type: application/json header so the server parses it correctly.

Gotchas

  • -d implies POST. If you pass data without -X, cURL defaults to POST. Set method: "POST" explicitly in fetch.
  • Basic auth. -u user:pass becomes an Authorization: Basic <base64> header. fetch has no -u shortcut, so encode it yourself or use the converter.
  • fetch does not throw on 4xx/5xx. Unlike many HTTP libraries, fetch() only rejects on network failure. Check response.ok to handle error status codes.

Convert it automatically

Pasting and remapping flags by hand is error-prone for long commands. The free cURL to JavaScript Converter parses a cURL command — respecting quotes, escapes, and the common flags — and outputs a ready-to-use fetch() call, entirely in your browser. Paste the command and copy the result.