node.jsnext.js

NextJS server side development behind corporate proxy


I'm writing some server-side API's in NextJS. These APIs fetch data from the Internet - and their fetches are being blocked as my development machine is behind a corporate proxy (the target environment is in the cloud - the problem is on my development machine on a corporate network).

How do I route my NextJS app's outbound fetches through a corporate proxy without changing the underlying code base?

--

Development machine is Mac OS X. NextJS version is 13.4.19. The package manager is yarn ("classic") - v1.22.19.

Have tried installing global-agent via yarn, setting GLOBAL_AGENT_HTTP_PROXY & GLOBAL_AGENT_HTTPS_PROXY in my project's .env file - then invoking node like this:

$ node -r global-agent/bootstrap -r cross-fetch/polyfill —no-experimental-fetch node_modules/next/dist/bin/next dev

In both cases server-side fetches still fail due to being blocked by the firewall.

I've tried setting proxy environment variables in the OS (HTTP_PROXY, HTTPS_PROXY). Python's requests package respects these environment variables and it is able to successfully connect to the API endpoints that I'm trying to access from within my NextJS app.

Have also tried configuring a proxy from within Yarn as described here - but as expected, this routes the yarn package manager's requests through the proxy, not those of my app.


Solution

  • I would recommend using Axios to fetch your data. Axios has in built features useful to help with proxy issues.

    Set your proxys like:

    Window terminal

    set HTTP_PROXY=http://<Proxy_host>:<port>  
    set HTTPS_PROXY=https://<Proxy_host>:<port>
    

    Linux terminal

    export HTTP_PROXY=http://<Proxy_host>:<port>  
    export HTTPS_PROXY=https://<Proxy_host>:<port>
    

    Alternatively change your code: No Auth:

    axios.get('https://httpbin.org/ip',
        {
            proxy: {
                protocol: 'http',
                host: '149.129.239.170',
                port: 8080,
            },
    
            responseType: 'json',
        }
    )
        .then(res => {
            console.log(res.data);
          }).catch(err => console.error(err))
    

    Auth:

    axios.get('https://httpbin.org/ip',
        {
            proxy: {
                protocol: 'http',
                host: 'proxy_host',
                port: portNumber,
                auth: {
                    username: '',
                    password: ''
    
                },
            },
    
        }
    )
        .then(res => {
            console.log(res.data);
          }).catch(err => console.error(err))