Proxy Port logo
How-to Guides > How to set up a proxy for node-fetch

How to set up a proxy for node-fetch

Node.js is a popular server-side JavaScript runtime that allows developers to build scalable and fast applications. When making HTTP requests in Node.js, you may need to use a proxy server to route traffic through a different IP address. This is useful for a variety of reasons, such as bypassing geo-restrictions or hiding your IP address.

In this article, we'll explore how to set up a proxy for node-fetch, a popular library for making HTTP requests in Node.js. We'll cover the steps needed to configure the HttpsProxyAgent module, which is used to create a proxy agent that can be passed to the fetch method. We'll also discuss some common use cases for using a proxy with node-fetch and provide some examples to help you get started.

To set up a proxy for node-fetch, you can use the HttpsProxyAgent module. Here are the steps to set up a proxy:

1. Install the https-proxy-agent package by running the following command in your terminal:
npm install https-proxy-agent
        
2. Import the HttpsProxyAgent module in your code:
const HttpsProxyAgent = require('https-proxy-agent');
        
3. Create a new instance of HttpsProxyAgent with your proxy URL:
const proxyUrl = 'http://your-proxy-url.com:port';
const proxyAgent = new HttpsProxyAgent(proxyUrl);

        
Note: Replace your-proxy-url.com with the actual URL of your proxy server and port with the port number on which your proxy server is running.

4. Pass the proxyAgent as an option to the fetch method:
fetch('https://example.com', { agent: proxyAgent })
.then(response => {
    // handle response
})
.catch(error => {
    // handle error
});
            
        
Note: Replace https://example.com with the URL you want to fetch.

That's it! Now you should be able to make requests through your proxy server using node-fetch.
Full code:
const HttpsProxyAgent = require('https-proxy-agent');

const proxyUrl = 'http://your-proxy-url.com:port';
const proxyAgent = new HttpsProxyAgent(proxyUrl);

fetch('https://example.com', { agent: proxyAgent })
.then(response => {
    // handle response
})
.catch(error => {
    // handle error
});
            
        
Proxy for scraping
More