---
title: "Superagent-Proxy: Ultimate Guide for Web Scraping with NodeJS"
description: "Find out how to use NodeJS, superagent, and superagent-proxy to scrape public data effectively."
url: "https://iproyal.com/blog/superagent-proxy-guide-nodejs/"
---

- [EN - English](https://iproyal.com/)
   
  [中文 - Chinese](https://iproyal.cn/)

[Book a Demo](https://iproyal.com/request-a-demo/) [Create Account](https://dashboard.iproyal.com/register/) [Create Account](https://dashboard.iproyal.com/register/) [Login](https://dashboard.iproyal.com/login/) [Login](https://dashboard.iproyal.com/login/)

[Book a Demo](https://iproyal.com/request-a-demo/)

[Back to blog](https://iproyal.com/blog/)

# Superagent-Proxy: Ultimate Guide for Web Scraping with NodeJS

[Justas Vitaitis](https://iproyal.com/blog/authors/justas-vitaitis/)

[Last updated - May 27, 2024 ‐ 6 min read](https://iproyal.com/blog/authors/justas-vitaitis/)

[Tutorials](https://iproyal.com/blog/category/tutorials/)

Superagent is a NodeJS HTTP client library that’s frequently used to send requests to APIs or servers. It’s also widely used for web scraping applications as **it’s a good foundational library for making HTTP requests.**

On its own, however, superagent only sends HTTP requests. **For web scraping applications, you’ll need much more.&#x20;**&#x4D;ost importantly, you’ll need a way to integrate proxies.

Superagent-proxy is an extension package that lets you do exactly that – **route traffic through proxies whenever you make HTTP requests.&#x20;**&#x57;e’ll go through both libraries, how they work, and how you can set up proxies for your web scraping project.

## Getting Started with Superagent-Proxy

### Prerequisites

Before all the proxy integration can begin, you’ll need a few things. First, an IDE that supports JavaScript and [NodeJS itself ](https://nodejs.org/en). **You’ll be using the IDE for development purposes, while NodeJS allows you to use JavaScript anywhere.&#x20;**&#x42;oth of them combined will let you use “superagent”.

While there’s only one NodeJS package you need to use, there’s a wide variety of IDEs you can choose from. **A few of the popular options are [Visual Studio Code ](https://visualstudio.microsoft.com/free-developer-offers/), [IntelliJ IDEA ](https://www.jetbrains.com/idea/download/?section=windows), and [Atom IDE ](https://atom-editor.cc/ide/).&#x20;**&#x49;ntelliJ IDEA is paid for JavaScript access, but it does have a 30-day free trial.

### Installation and Setup

Once you have NodeJS installed and the IDE at the ready, **open up the Terminal to install both libraries:**

```javascript
npm install superagent superagent-proxy
```

If your IDE doesn’t start you off with a “.js” file, **you’ll need to create one on your own.&#x20;**&#x59;ou can use the IDE or simply create a file through regular OS means.

You’ll then need to **import both of the libraries&#x20;**&#x74;o make use of the functions stored within.

```javascript
const superagent = require('superagent');
require('superagent-proxy')(superagent); // Extends superagent request class with proxy capabilities
```

**“Const superagent” is more or less equal to “import superagent” for the means of getting access to the inbuilt functions.&#x20;**&#x4D;ost web resources, however, will recommend using “const superagent” over “import superagent” as it simplifies programming.

### Sending a GET Request

Before you can even think of using “superagent-proxy” **you’ll need to first set up communication with a server.&#x20;**&#x49;f you’re not sending any requests to an external server, there’s no point in setting up a proxy.

```javascript
const superagent = require('superagent');
require('superagent-proxy')(superagent); // Extends superagent request class with proxy capabilities

const url = 'https://iproyal.com'; // The URL you want to scrape

superagent
    .get(url)
    .then(res => {
        console.log('Data retrieved:', res.text); // Output the content directly to the console
    })
    .catch(err => {
        console.error('Error fetching data:', err);
    });
```

We’ve added a few new lines. First, we **create a new constant&#x20;**(it cannot be changed during execution) with our desired URL.

Once that’s established, we **call the “superagent” library and use the method “.get(url)”.&#x20;**&#x53;ince our constant is “url”, we’re simply pulling the URL from our constant.

Our code proceeds, after receiving some information from the URL, to take the response (“res”) and outputs the data to the console. We also **add “Data retrieved:”&#x20;**&#x62;efore outputting the response text (“res.text”).

In case an error occurs, we **use the “.catch()” method to implement some error handling.&#x20;**&#x49;f an error occurs, instead of throwing some exception that’s hard to understand, the error will be output into the console with some additional information.

### Implementing Rotating Proxies

Once we’re communicating with a website or API, we can begin using proxy servers. **Our “superagent-proxy” library works primarily with HTTPS proxies.&#x20;**&#x49;f you want to use SOCKS5 instead of HTTPS proxies, there’s a similar library for it, called “socks-proxy-agent”.

Most of the steps for “socks-proxy-agent” will be nearly identical, so we’ll only be covering the usage of HTTPS proxies only. **These proxy servers work with “superagent-proxy” and are significantly more popular as well.**

```javascript
const superagent = require('superagent');
require('superagent-proxy')(superagent); // Extends superagent with proxy capabilities

const url = 'https://iproyal.com'; // The URL you want to scrape
const proxy = 'http://your-proxy.com:port';

superagent
  .get(url)
  .proxy(proxy)
  .then(res => {
    console.log('Data retrieved:', res.text);
    // Here you can process the data or store it as needed
  })
  .catch(err => {
    console.error('Error fetching data:', err);
  });
```

All we’re doing is adding another constant “proxy”, which points to our HTTP proxy server IP address and port. We then **call “proxy(proxy)” in the superagent function.**

While such an implementation can work perfectly fine, your proxy servers must support IP whitelisting. Additionally, since there’s only one address, **your provider must supply rotating proxies with a single endpoint.**

Some providers don’t do either. **Let’s start with authentication:**

```javascript
const superagent = require('superagent');
require('superagent-proxy')(superagent); // Extend superagent with proxy support

const url = 'https://example.com/data'; // The URL you want to request
const proxy = 'http://username:password@proxyhost:port'; // Your authenticated proxy

superagent
  .get(url)
  .proxy(proxy) // Set the proxy with authentication
  .then(res => {
    console.log('Data retrieved:', res.text); // Output the fetched data
  })
  .catch(err => {
    console.error('Error fetching data:', err); // Error handling
  });
```

We simply change the proxy server address to one that has the username and password in the URL. Take note that **some providers may use different combinations,&#x20;**&#x62;ut they should be providing a guide on how to integrate proxy servers.

You may also use the authentication header for **a more secure but more complicated way to authorize proxies.&#x20;**&#x54;ake note that not all proxy providers will support such authentication:

```javascript
const superagent = require('superagent');
require('superagent-proxy')(superagent); // Extend superagent with proxy support

const url = 'https://example.com/data'; // URL to fetch
const proxy = 'http://proxyhost:port'; // Proxy server (no credentials in URL)

// Username and password for proxy
const username = 'yourUsername';
const password = 'yourPassword';

// Encode username and password in Base64 for the Proxy-Authorization header
const base64Credentials = Buffer.from('${username}:${password}').toString('base64');
const proxyAuthHeader = 'Basic ${base64Credentials}';

superagent
  .get(url)
  .proxy(proxy) // Set the proxy without embedded credentials
  .set('Proxy-Authorization', proxyAuthHeader) // Manually set the proxy authorization header
  .then(res => {
    console.log('Data retrieved:', res.text); // Output the fetched data
  })
  .catch(err => {
    console.error('Error fetching data:', err); // Error handling
  });
```

We now first **create two constants that store our username and password as strings.&#x20;**&#x53;ince we’ll be using the proxy authentication header, it’s encoded in base64, so we need to turn our strings to such an encoding.

That’s what “base64Credentials” does: it creates a buffer that takes the strings from our username and password constants and converts them to base64. We then **create a proxy authorization header, which we pass during the superagent function call.**

### Implementing IP Addresses as Lists

**Some providers may give you lists of IP addresses instead of a single endpoint with rotating proxies.&#x20;**&#x59;ou’ll have to then create your proxy rotation logic.

One of the simplest ways is to simply pick IP addresses at random with each request. Let’s start by setting up a list for our IPs:

```javascript
const superagent = require('superagent');
require('superagent-proxy')(superagent);

// List of proxies
const proxies = [
    'http://username:password@proxyhost1:port',
    'http://username:password@proxyhost2:port',
    'http://username:password@proxyhost3:port',
    // Add more proxies as needed
];
```

We’ll then create a function to pick a proxy at random from our list:

```javascript
const superagent = require('superagent');
require('superagent-proxy')(superagent);

// List of proxies
const proxies = [
    'http://username:password@proxyhost1:port',
    'http://username:password@proxyhost2:port',
    'http://username:password@proxyhost3:port',
    // Add more proxies as needed
];

function sendRequestWithRandomProxy(url) {
    const proxy = proxies[Math.floor(Math.random() * proxies.length)]; // Select a random proxy
    console.log(`Using proxy: ${proxy}`);

    superagent
        .get(url)
        .proxy(proxy)
        .then(res => {
            console.log('Data retrieved:', res.text); // Output the fetched data
        })
        .catch(err => {
            console.error('Error fetching data:', err); // Error handling
        });
}

// Example: Send multiple requests using random proxies
sendRequestWithRandomProxy(targetURL);
sendRequestWithRandomProxy(targetURL);
sendRequestWithRandomProxy(targetURL); // Each call picks a different random proxy
```

We can then simply call the function for each URL. Create a “for” list if you have a lot of URLs to go through.

## Picking the Correct Proxies

There are a few different types of proxies that may significantly influence the performance of your web scraping project:

- [Residential proxies ](https://iproyal.com/residential-proxies/)– **IPs acquired from household devices.&#x20;**&#x47;reat for use cases where speeds are not as important and bot detection rates are high.
- Datacenter proxies – **IPs acquired from data centers.&#x20;**&#x47;reat for use cases where speeds are most important and detection rates are not that high.
- ISP proxies – **a combination of residential and datacenter proxies.&#x20;**&#x42;est for use cases where lots of IPs are not required, but speed and undetectability is important.

Most of these proxies will integrate through the same methods we’ve outlined above. Take note that some proxies may be charged per IP without any bandwidth limitations, while others are charged by GBs.

[Create Account](https://dashboard.iproyal.com/)

[Author](https://iproyal.com/blog/authors/justas-vitaitis/)

[Justas Vitaitis](https://iproyal.com/blog/authors/justas-vitaitis/)

[Senior Software Engineer](https://iproyal.com/blog/authors/justas-vitaitis/)

Justas is a Senior Software Engineer with over a decade of proven expertise. He currently holds a crucial role in IPRoyal’s development team, regularly demonstrating his profound expertise in the Go programming language, contributing significantly to the company’s technological evolution. Justas is pivotal in maintaining our proxy network, serving as the authority on all aspects of proxies. Beyond coding, Justas is a passionate travel enthusiast and automotive aficionado, seamlessly blending his tech finesse with a passion for exploration.

[Learn More About Justas Vitaitis ](https://iproyal.com/blog/authors/justas-vitaitis/)[Meet all Writers](https://iproyal.com/blog/authors/)

Share on

### In This Article

- [Getting Started with Superagent-Proxy](https://iproyal.com/blog/superagent-proxy-guide-nodejs/#Getting-Started-with-Superagent-Proxy)
- [Picking the Correct Proxies](https://iproyal.com/blog/superagent-proxy-guide-nodejs/#Picking-the-Correct-Proxies)

Ready to get started?

[Register now](https://dashboard.iproyal.com/register/)

Data News in Your Inbox

No spam whatsoever, just pure data gathering news, trending topics and useful links. Unsubscribe anytime.

No spam. Unsubscribe anytime.

## Related articles

[View all](https://iproyal.com/blog/category/tutorials/)

[Tutorials](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

## [The Most Common Payment Processing Obstacles and Solutions for SaaS Companies](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

[Here are the most common payment processing obstacles SaaS companies face and the solution that helped us focus on growth and our services!](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

[August 8, 2022](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

[3 min read](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

[Tutorials](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

## [Easy Programmatic SEO with WordPress](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

[Our fourth and final entry in the pSEO series explains how to combine programmatic SEO with WordPress using plugins or code snippets.](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

[March 30, 2023](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

[10 min read](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

[Tutorials](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)

## [API for Dummies — The Coder’s and No-coder’s Guide](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)

[Learn API basics with this guide for coders and non-coders. Discover the different components of an API call.](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)

[June 1, 2023](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)

[11 min read](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)
