ScreenshotNeo

BlogGuides

cURL JavaScript Guide: Convert Commands to JavaScript

Convert a cURL request to JavaScript fetch, Node.js, or Axios. Learn the DevTools workflow, review generated code, and handle runtime differences safely.

By the ScreenshotNeo team29 September 202611 min read

cURL JavaScript Guide: Convert Commands to JavaScript

To convert a cURL command to JavaScript, copy the request from DevTools, paste it into curlconverter’s JavaScript converter, select the target runtime, then review and run the generated code. Treat the result as a translation starting point: check the URL, method, headers, credentials, body, redirects, compression, and error handling before relying on it.

This guide covers browser fetch, Node.js targets such as Axios, DevTools capture, repeatable conversion with the CLI or library, common fidelity issues, and safe handling of copied credentials.

1. Convert a cURL command in the browser

  1. Open the browser’s developer tools and select the Network tab.
  2. Reproduce the action that sends the request. Find the relevant network entry.
  3. Right-click the request and choose Copy → Copy as cURL. Safari and Firefox also provide a copy-as-cURL option; on a Mac, Ctrl-click or a two-finger click may open the context menu.
  4. Go to curlconverter.com/javascript and paste the command.
  5. Choose the output target. For browser code, use JavaScript fetch; for Node, choose an appropriate Node target such as Axios or node-http.
  6. Review the generated method, URL, query, headers, authentication, and body. Remove values that should not be carried into your application.
  7. Run the code in the intended environment and compare its response and behavior with the original cURL command.

The converter project also lists targets including node-axios, node-http, node-got, node-ky, node-request, and node-superagent, as well as JavaScript, jQuery, and XHR. Pick based on where the code runs and the dependencies your project already uses; generated targets can have different defaults and APIs.

Capture the request in DevTools, convert it, then review the generated JavaScript.
Capture the request in DevTools, convert it, then review the generated JavaScript.

2. Understand the generated fetch request

A typical conversion maps the cURL method, URL, headers, and body onto the Fetch API. This runnable browser example shows the shape; substitute the endpoint and request data from your own command:

const response = await fetch("https://api.example.com/v1/items", {
  method: "GET",
  headers: {
    Accept: "application/json"
  }
});

if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}

const data = await response.json();
console.log(data);

In a browser module or an async function, await is available as shown. For a JSON POST, set the content type and serialize the data:

const payload = { name: "Example" };

const response = await fetch("https://api.example.com/v1/items", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json"
  },
  body: JSON.stringify(payload)
});

if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}

const result = await response.json();
console.log(result);

Fetch rejects its promise for some network failures, but an HTTP error status such as 404 or 500 still produces a response. Check response.ok or response.status explicitly. Parse the body according to its real format: use response.json() for JSON, response.text() for text, or response.blob() for binary data.

Map the cURL pieces deliberately

cURL detail What to check in JavaScript
URL and -G/--data-urlencode Confirm query parameters are in the URL and encoded exactly once. Use URL and URLSearchParams for dynamic values.
-X or inferred method Confirm the method. A request with data may imply POST in cURL; generated code should preserve the intended method.
-H Review every header, especially authorization, cookies, content type, and browser-specific headers.
-d, --data, --data-raw Check whether the body is form data, JSON, or plain text. JSON needs serialization when built as an object.
-u Confirm how authentication is represented and avoid embedding a reusable secret in client-side code.
-F Multipart form bodies and file inputs need runtime-specific handling; browser code commonly uses FormData.
-L Check redirect behavior for the chosen runtime. Defaults and control options differ.
--compressed Check compression behavior. Runtimes may handle gzip decompression differently from cURL.

3. Choose browser JavaScript or Node.js

“JavaScript” does not identify one runtime. Browser fetch runs under browser security rules, including same-origin and CORS restrictions. Node.js runs outside that browser boundary and can use Node-specific packages and APIs. A command that succeeds in a terminal can therefore fail from a web page even when the URL and headers appear identical.

Target Use it when Review carefully
Browser fetch The request belongs in a web page and the server allows it. CORS, cookies and credentials, browser-managed headers, and exposure of secrets to visitors.
Node native HTTP target You want a Node-oriented result without choosing a higher-level client. Generated API details, response stream handling, redirects, and compression.
Axios Your Node or browser project already uses Axios or needs its request/response interface. Installation, error shape, body serialization, and option differences from cURL.
Got, Ky, SuperAgent, or another listed target Your project already uses that client or its API suits the application. Dependency availability and that client’s own defaults. Do not assume targets are interchangeable.

Node.js with Axios

Select the Axios target in the converter for a translation of your actual command. For a basic request, the resulting program follows this general pattern. Install Axios in the project first with npm install axios if it is not already available.

import axios from "axios";

const response = await axios.get("https://api.example.com/v1/items", {
  headers: {
    Accept: "application/json"
  }
});

console.log(response.data);

For a POST, Axios accepts the body as the second argument:

import axios from "axios";

const response = await axios.post(
  "https://api.example.com/v1/items",
  { name: "Example" },
  { headers: { Accept: "application/json" } }
);

console.log(response.data);

These examples illustrate Axios conventions; check the converted request for the exact headers and payload. Axios and fetch do not expose failures identically. Make error handling explicit and inspect the response status and data available in the error object for your installed client version.

4. Protect credentials copied from DevTools

A copied browser request may include session cookies, bearer tokens, API keys, or other personal request data. Treat a copied cookie like a password. The converter warns that copied commands can contain sensitive values. Its browser page says conversion happens entirely in the browser and that it does not transmit or record the command. Even so, do not paste a live credential into a shared document, issue, chat, or committed source file.

  • Before sharing a command, remove or replace Cookie, Authorization, API key, and session values.
  • If a credential was exposed, revoke or rotate it using the service that issued it.
  • Keep server credentials on a trusted server. Anything embedded in browser JavaScript can be inspected by visitors.
  • In Node projects, read secrets from environment variables or a secret manager rather than hard-coding them.
  • Remove irrelevant headers copied from the browser. Some are browser-controlled and cannot be set by page JavaScript.

5. Convert repeatedly with the CLI or library

For repeatable work, install the curlconverter CLI globally or add its library to a project. The project documents Node 12 or later as a requirement. Check the project’s current documentation for the exact commands and supported language flags before wiring conversion into a script.

npm install --global curlconverter

The CLI accepts a cURL command or input from standard input and provides a language flag. For example, after installation, pass a quoted command to the CLI using its documented invocation, or pipe a saved command into it. Shell quoting matters: nested quotes, variables, and substitutions can be interpreted by your shell before curlconverter sees them.

Install the package locally when conversion is part of a Node tool:

npm install curlconverter

The library exposes conversion functions that work with command strings or parsed argument arrays. Consult the package documentation for the exported function names and target names for your installed version. Prefer a command string when you need the converter to parse the same text a person copied; parsed arguments can be useful when another step in your tool already tokenizes the input.

6. Check fidelity against cURL

Generated code is not guaranteed to reproduce every shell command or cURL behavior. The project implements much of cURL argument parsing, understands several Bash constructs, converts JSON data to native objects, and can report warnings. Its documented limitations matter when the command is complicated:

  • HTTP only: non-HTTP cURL protocols are outside the supported conversion scope.
  • Incomplete Bash parsing: the parser does not support all Bash syntax.
  • Shell variables and nested commands: nontrivial variables or nested subcommands can prevent valid output because the shell may expand or execute them before the converter can interpret them.
  • Runtime defaults: redirects and gzip decompression can differ from cURL in the generated target.
  • Different client APIs: browser fetch, Node HTTP, Axios, Got, and other targets have distinct methods for errors, streams, files, and configuration.

When exact equivalence matters, make a small comparison checklist: same final URL and query, same method, same body bytes and content type, same authentication, same redirect destination, and same response decoding. Test against a safe endpoint or a development account before using a converted request in a production workflow.

7. Troubleshooting

Symptom Likely cause Fix
Converter output has broken quoting or misses an argument The command contains shell substitutions, nested commands, or Bash syntax the parser does not support. Resolve shell variables to safe literal values, simplify the command, then convert. Keep secrets replaced with placeholders.
Request works in terminal but browser reports a CORS error The remote server does not allow the page’s origin or requested headers. Configure the server’s CORS policy if you control it, or make the request from your backend. A client-side translation cannot bypass browser policy.
JavaScript reports success for a 404 or 500 Fetch resolves for HTTP responses; it does not treat every non-2xx status as a rejected promise. Check response.ok and handle the status before parsing the body.
Server says the JSON body is malformed The body was serialized incorrectly, or the content type does not match its format. For an object passed to fetch, use JSON.stringify(value) and set Content-Type: application/json. Compare the final transmitted body with cURL.
Authentication fails after conversion A cookie or authorization value was omitted, expired, copied incorrectly, or is not appropriate for the target runtime. Use a valid credential through the right mechanism. Keep it secret and confirm whether the endpoint expects a cookie, bearer token, or another scheme.
Redirect ends at a different page The generated runtime follows or exposes redirects differently from cURL, or the original command used -L. Inspect the redirect chain and destination. Configure the chosen client’s redirect behavior where supported, then compare results.
Compressed response looks different or parsing fails Compression negotiation or decompression differs between cURL and the JavaScript runtime. Inspect response headers and the client’s decompression behavior. Avoid blindly copying Accept-Encoding headers managed by the runtime.
Multipart upload fails The converted body retained a shell file path or boundary/header that does not match the runtime’s multipart encoder. Use the target runtime’s FormData or file-stream API. Let its multipart implementation set the matching boundary when appropriate.
Node cannot import the generated package The selected target needs a dependency, or the project’s module format differs from the generated syntax. Install the package named by the target and align imports with the project’s CommonJS or ES module setup.
Converted command is valid but returns different data Headers, query encoding, body bytes, cookies, or runtime defaults differ. Compare request details in DevTools or server logs. Remove incidental headers one at a time and verify the endpoint’s documented contract.

8. Performance, reliability, and cost

The converter translates a request; it does not make the destination API faster or guarantee its availability. Runtime choice affects dependency size, connection handling, and how you process responses, so use the client already supported by your application where practical. For large responses, prefer streaming APIs when available rather than buffering the entire body in memory. For repeated requests, follow the selected client’s guidance for connection reuse, timeouts, and retries.

Do not add automatic retries to non-idempotent operations without considering duplicate side effects. A timeout does not prove the server failed to process a request. For production calls, set an application-appropriate timeout, handle non-success statuses, and retry only when the endpoint and request semantics make that safe.

There is no converter benchmark or latency figure in the project sources used here. Conversion is useful for saving translation effort, but verify the resulting application under its real workload. Any monetary cost comes from the API being called, its hosting, and chosen libraries or infrastructure; curlconverter’s conversion step does not define the remote service’s pricing.

9. Or skip the browser setup

If your goal is to capture a website rather than reproduce an arbitrary API request, ScreenshotNeo provides a one-call screenshot API and an MCP server. It returns a PNG, JPEG, WebP, or PDF from a URL. See the ScreenshotNeo API documentation.

ScreenshotNeo removes supported consent banners, popups, and chat widgets before capture.
ScreenshotNeo removes supported consent banners, popups, and chat widgets before capture.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; those steps can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits cost nothing, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.

Create a free ScreenshotNeo account to get 1,000 screenshots a month with no card.

10. FAQ

Can I convert cURL to JavaScript without installing anything?

Yes. Use the browser converter at curlconverter.com/javascript. It says the conversion runs locally in the browser and that it does not transmit or record entered commands.

Can DevTools convert any request into a cURL command?

DevTools can copy network requests as cURL in Chrome, Safari, and Firefox. The copied command may still contain credentials and browser-specific details, and conversion support does not cover every shell construct.

Should I use fetch or Axios?

Use the API already supported by your runtime and project. Browser fetch needs no additional client library but is subject to browser security rules; Axios is a separate client with its own installation and error conventions. Compare the behavior you need rather than assuming generated targets match.

Can the converter safely handle secrets?

The browser page states commands are not transmitted or recorded, but copied requests can contain sensitive values. Remove or rotate secrets before sharing a command and keep production credentials out of browser code and source control.

Sources