How to Use cURL in JavaScript: Comprehensive Guide and Alternatives
TutorialsLearn how to use cURL in JavaScript by converting commands to Fetch and Axios. Explore Node.js alternatives for handling secure HTTP requests and data transfer.

Karolis Toleikis
Key Takeaways
-
In client-side code, cURL commands must be translated into native functions like fetch() or axios because browsers cannot execute shell commands directly.
-
The Fetch API and Axios are the standard ways to handle HTTP requests and JSON data in modern JavaScript applications.
-
Node.js offers flexibility on the server side with the native global Fetch API, though you can also use packages like node-libcurl or execute commands directly via child_process.
Developers frequently need to move data between apps and servers. You might start by testing a connection in your terminal, but eventually, you’ll need to integrate that logic into your code.
We’ll cover everything you need to know about cURL JavaScript workflows and how to translate terminal commands into functional code.
What Is cURL and Why Use It?
cURL is a widely used command-line tool that allows you to transfer data across various network protocols. It’s also completely free and open-source, which is why developers rely on it heavily for making HTTP requests without needing a graphical interface. It’s fast, powerful, and pre-installed on macOS, Linux, and modern Windows systems.
You can use it to test if an API is working or to automate file downloads. Since it works on the command line, it’s perfect for quick scripting and automation. The cURL command-line tool gives you raw control over the request, which helps with debugging complex network issues.
Why JavaScript Cannot Run cURL Natively
JavaScript has its own native HTTP mechanisms: fetch() and XMLHttpRequest in browsers, the http/https modules (and now fetch()) in Node.js. These serve the same purpose as cURL (making network requests), but they’re distinct APIs, not wrappers around cURL.
Additionally, browsers run JavaScript code in a secure sandbox to protect users, preventing web page scripts from accessing your system’s terminal or executing shell commands.
Consequently, you cannot simply paste cURL commands into your browser’s console or HTML code. You must use JavaScript alternatives that achieve the same goal.
While Node.js can execute shell commands, relying on external cURL processes is often slower and less efficient than using native JavaScript HTTP clients.
Converting cURL Commands Into JavaScript
You can translate any cURL request into JavaScript by mapping the flags to specific functions.
Mapping cURL Parameters to Fetch and Axios
To build a request in JavaScript, you need to understand which cURL options correspond to which code parameters:
- -X flag. Specifies the HTTP method, such as GET or POST .
- -H flag. Sets the headers, which often include the user agent or content type.
- -d or –data flag. Contains the request body or payload you want to send.
When using the Fetch API, you pass these as an options object. You’ll define the method, an object for headers, and a body property for your data. Libraries like Axios handle JSON data stringification automatically and will implicitly add the Content-Type: application/json header for you, so you don’t need to map that flag manually.
Practical Examples: From cURL to Fetch and Axios
Let’s look at a side-by-side comparison. Suppose you have the following cURL request that sends a login attempt.
Original cURL
curl -X POST https://jsonplaceholder.typicode.com/users \
-H "Content-Type: application/json" \
-H "User-Agent: MyApp/1.0" \
-d '{"username":"user","pass":"1234"}'
Using Fetch
const login = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'User-Agent': 'MyApp/1.0'
},
body: JSON.stringify({
username: 'user',
pass: '1234'
})
});
const data = await response.json();
console.log(data);
};
login();
Using Axios
const axios = require('axios');
const login = async () => {
const response = await axios.post('https://jsonplaceholder.typicode.com/users', {
username: 'user',
pass: '1234'
}, {
headers: {
'User-Agent': 'MyApp/1.0'
}
});
console.log(response.data);
};
login();
These examples show how easily cURL commands translate into code. We set the User-Agent to mimic the original request. Note that while it works in Node.js, browsers forbid scripts from modifying the User-Agent header for security reasons.
Running HTTP Requests in Browsers Using JavaScript
When you are working on a web page, you have specific tools available to replace cURL commands.
Using the Fetch API
The Fetch API is the modern standard for making requests in browsers. Fetch is built directly into the browser, so you don't need to install anything. It uses asynchronous JavaScript to handle network operations without freezing the screen.
Here’s how you handle JSON responses with an async function:
async function getData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
getData();
The async function waits for the data to arrive and then parses the JSON. It also includes basic error handling to catch connection issues.
Using AJAX With jQuery for cURL-like Requests
Older websites often use jQuery to handle HTTP requests. It’s useful if your project already has jQuery installed, since the $.ajax method is very powerful and can replicate most cURL commands.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/users',
method: 'GET',
headers: {
'X-Custom-Client': 'MyBrowser/1.0', // Use a custom header instead
'Authorization': 'Bearer token123'
},
success: function(data) {
console.log('Received JSON data:', data);
},
error: function(xhr) {
console.log('Error:', xhr.statusText);
}
});
It handles response headers and parsing automatically, and provides a familiar syntax for developers transitioning from older codebases. You can also run these in your browser, but we wouldn’t recommend paying ajax too much attention – fetch() has made it somewhat obsolete.
Common Browser Challenges: CORS and Security
Browsers have strict security rules. cURL commands in a terminal can go anywhere, but browser requests are limited by CORS (Cross-Origin Resource Sharing). If you try to fetch data from a different domain, the browser may block the request entirely (called a preflight check) or prevent your code from reading the response unless the server explicitly allows it.
Additionally, browsers strictly control the user agent header. You can't always change it freely like you can with a command-line tool. It prevents malicious code from pretending to be something it isn't.
Running cURL-like Requests in Node.js
The server-side environment offers more flexibility. You can choose between running shell commands or using native libraries.
Using Child Process
Node.js allows you to execute shell commands directly. You can run cURL commands exactly as you would in a terminal by using the child_process module.
const { exec } = require('child_process');
exec('curl -I https://www.google.com', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
});
It’s useful for quick scripts, but it has downsides. Parsing the output is difficult because it comes as a simple text string rather than structured JSON data.
Using node-libcurl
For a true cURL JavaScript experience, you can use the node-libcurl package, which provides bindings to the actual cURL library used by the command-line tool. It’s very fast and supports complex features.
First, you must install the node-libcurl package:
npm install node-libcurl
Then you can use it in an async function:
const { Curl } = require('node-libcurl');
const curl = new Curl();
curl.setOpt('URL', 'https://jsonplaceholder.typicode.com/users');
curl.setOpt('POST', true);
curl.setOpt('POSTFIELDS', JSON.stringify({ key: 'value' }));
curl.on('end', function (statusCode, data, headers) {
console.log(statusCode);
this.close();
});
curl.on('error', curl.close.bind(curl));
curl.perform();
The node-libcurl package is powerful, but it requires compiling native dependencies, which can sometimes cause installation issues on different operating systems.
Using Popular HTTP Client Libraries
Most server-side developers prefer using the built-in global Fetch API or robust third-party packages like Axios. These libraries are safer and easier to maintain than executing cURL commands via shell.
Here is a reliable POST request using Axios with proxy authentication:
import axios from 'axios'; // Or const axios = require('axios'); in older Node.js
async function sendData() {
try {
const res = await axios.post('https://jsonplaceholder.typicode.com/users', {
id: 123
}, {
proxy: {
protocol: 'http',
host: '127.0.0.1',
port: 9000,
auth: { username: 'user', password: 'pwd' }
},
headers: { 'User-Agent': 'SecureBot/2.0' }
});
console.log(res.headers); // Access response headers
} catch (err) {
console.error(err.message); // Clean error messages
}
}
It simplifies proxy authentication significantly. You don't need to format a complex proxy string as you would in the command line.
Benefits of Using Axios/Fetch Over Shell cURL
Using a dedicated HTTP client in JavaScript is generally better than running shell commands. Libraries provide structured error messages and automatic transformation of JSON responses. They also handle asynchronous JavaScript flows naturally with Promises.
Furthermore, executing cURL commands via child_process can be a security risk. If you accept user input and pass it to a shell command, an attacker might inject malicious commands. Native libraries sanitize inputs and prevent these vulnerabilities. They also give you easy access to response headers and status codes without parsing raw text.
Conclusion
Understanding cURL JavaScript integration gives you powerful options for handling data. While you can't run the command-line tool natively in a browser, modern alternatives like the Fetch API and Axios provide excellent functionality.
You can simulate almost any HTTP-based command-line request using these libraries. Just remember to manage error-handling properly and respect the differences between server-side and browser environments. Using the right tools ensures your network requests are secure, efficient, and easy to maintain.