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
HTTP error! Status: ${response.status});
}
const data = await response.json();
console.log('Success:', data);
return data;
} catch (error) {
if (error.name === 'TimeoutError') {
console.error('Request timed out after 8 seconds.');
} else {
console.error('Fetch failed:', error.message);
}
}
}
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:
Handling Streaming Responses & Server-Sent Events (SSE)
A major advantage of modern browser fetch() over traditional cURL CLI commands is native support for response body streaming via the ReadableStream API. This is foundational for modern AI applications (like streaming OpenAI or Gemini text completions token-by-token) and Server-Sent Events (SSE).
Timeout Management & Request Cancellation via AbortController
In cURL, setting a request timeout is achieved using the --max-time 10 flag. In JavaScript fetch(), requests do not have a built-in timeout parameter and will hang indefinitely if the remote server fails to close the connection.
The modern standard for enforcing timeouts and cancelling obsolete requests (e.g. when a user navigates away from a page) is AbortController:
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?