Migrating from cURL to Fetch API: The Complete Developer Guide
Whenever third-party API providers (like Stripe, OpenAI, GitHub, or Twilio) document their REST endpoints, their code samples almost always lead with a terminal cURL command.
While cURL is ideal for quick command-line verification, frontend developers and Node.js engineers must translate these CLI flags into modern, idiomatic JavaScript using the Fetch API. In this guide, we map common cURL parameters to Fetch options, explain body serialization, and implement modern timeout patterns with AbortSignal.
1. Mapping cURL Flags to Fetch Options
| cURL Flag | Fetch Equivalent | Example Usage |
|---|---|---|
-X, --request |
method: 'POST' |
Specifies HTTP verb (GET, POST, PUT, DELETE) |
-H, --header |
headers: { ... } |
Sets custom request headers (Authorization, Content-Type) |
-d, --data |
body: JSON.stringify(...) |
Request body payload |
-u, --user |
headers: { 'Authorization': 'Basic ...' } |
Base64-encoded username and password |
2. Translating a Complete Real-World Example
Consider this standard terminal cURL command sending a JSON payload with a Bearer authentication token:
The Idiomatic JavaScript Fetch Implementation
fetch() only rejects a Promise on network failure or if the request was aborted. A 404 Not Found or 500 Server Error is still considered a resolved Promise. Always verify response.ok!
3. Handling FormData and File Uploads
When translating cURL multipart uploads (e.g. curl -F "file=@photo.jpg"), never manually set the Content-Type header. The browser must set it automatically along with the dynamic multipart boundary:
4. Try Our Free Client-Side cURL to Fetch Converter
Want to paste raw cURL commands and instantly get clean, copy-pasteable JavaScript code blocks without uploading your API keys?