DEV Community

Rajesh Nautiyal
Rajesh Nautiyal

Posted on • Originally published at rajesh-nautiyal.Medium on

How to Proxy API Requests in NodeJs Using a SOCKS Proxy with Axios

Introduction

When developing applications, you might encounter scenarios where certain APIs are accessible only from specific IP addresses. This can pose a challenge if you’re working locally and your local IP is not whitelisted. One effective solution is to use a SOCKS proxy to route your API requests through a server with an approved IP address. In this blog post, we’ll walk through the process of setting up a Fastify server to make API requests using Axios, routed through a SOCKS proxy.

Problem Statement

You have an API (https://example.com/countries) that returns country data but is accessible only from whitelisted IPs. Your server, deployed at a whitelisted IP, can access this API. However, while developing locally, you need to make API requests from your local machine (e.g., http://localhost:3000/getcountries) and route these requests through your server to access the restricted API.

Solution Overview

We’ll set up a SOCKS proxy using SSH, configure a NodeJs server to make proxied API requests using Axios and route these requests through the SOCKS proxy. Here’s a step-by-step guide to achieve this.

Step-by-Step Guide

1. Set Up the SOCKS Proxy

First, establish a SOCKS proxy using SSH. Run the following command in your terminal:

ssh -D 5001 rajesh@xyz.amazonaws.com
Enter fullscreen mode Exit fullscreen mode
  • -D 5001: Specifies dynamic application-level port forwarding on port 5001(You can use any other port).
  • rajesh@xyz.amazonaws.com: Replace with your actual SSH user and server address.

Install the http-proxy-to-socks package in your local system:

npm install -g http-proxy-to-socks
Enter fullscreen mode Exit fullscreen mode

Redirect your local requests to the tunnel connection

hpts -s 127.0.0.1:5001 -p 8080
Enter fullscreen mode Exit fullscreen mode

If you have followed till here, you can add the custom proxy to your Postman app and call the API:

  • Go to postman➝settings➝proxy
  • Select custom proxy
  • Add the host: 127.0.0.1
  • Add the port: 8080

2. Install Required Packages

Ensure you have Node.js and npm installed, then install Fastify, Axios, and socks-proxy-agent:

npm install fastify axios socks-proxy-agent
Enter fullscreen mode Exit fullscreen mode

3. Configure the Fastify Server

Create a file (e.g., server.js) and set up your Fastify server with Axios to use the SOCKS proxy. Here’s the complete code:

const fastify = require('fastify')({ logger: true });
const axios = require('axios');
const { SocksProxyAgent } = require('socks-proxy-agent');

// Create a SOCKS proxy agent
const agent = new SocksProxyAgent('socks://127.0.0.1:5001');
// Fastify GET route
fastify.get('/getCountries', async (request, reply) => {
    try {
        const response = await axios({
            method: 'get',
            url: 'https://example.com/countries',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            httpAgent: agent
            httpsAgent: agent
        });
        reply.send(response.data);
    } catch (error) {
        fastify.log.error('Error creating user:', error.message);
        reply.status(500).send({ error: 'Failed to create user' });
    }
});
const start = async () => {
    try {
        await fastify.listen(3000);
        fastify.log.info(`Server running at http://localhost:3000`);
    } catch (err) {
        fastify.log.error(err);
        process.exit(1);
    }
};
start();
Enter fullscreen mode Exit fullscreen mode

4. Start Your Fastify Server

Run your Fastify server:

node server.js
Enter fullscreen mode Exit fullscreen mode

5. Test the Endpoint

Use tools like Postman or curl to send a POST request to your local Fastify server endpoint (http://localhost:3000/getCountries) and verify that it returns the expected data:

curl -X POST http://localhost:3000/getCountries
Enter fullscreen mode Exit fullscreen mode

Conclusion

By following these steps, you can successfully route your API requests through a SOCKS proxy using Fastify and Axios. This setup allows you to develop locally while accessing APIs restricted to specific IPs. If you encounter issues, check your proxy settings, and network configurations, and ensure your SSH tunnel is active.

I hope this guide helps you set up your development environment effectively. Happy coding!

Top comments (0)