简体   繁体   中英

next.js SSR set proxy

for network reasons,nextjs Requesting API in getServerSideProps will fail,in dev,I want to configure the proxy, but I can't find a way,Is there any solution please? (Sorry, my English is not good)

First you need to install the following npm packages:

    "https-proxy-agent": "5.0.1",
    "net": "1.0.2",
    "tls": "0.0.1",

Then create baseFetchOptions.ts

const HttpsProxyAgent = require('https-proxy-agent');

const baseFetchOptions: any = {};
if(process.env.HTTP_PROXY) {
    const proxyUrl = new URL(process.env.HTTP_PROXY);
    baseFetchOptions.agent = new HttpsProxyAgent({
        host: proxyUrl.hostname,
        port: proxyUrl.port
    });
}

export default baseFetchOptions;

Now you can use it. Example:

  import baseFetchOptions from "@/utils/baseFetchOptions";

  const response = await fetch(
    "https://...",
    {
      ...baseFetchOptions,
      method: "POST",
    },
  );

If you want to test it, you can use squid docker container.

"dev": "HTTP_PROXY=http://127.0.0.1:3128/ next dev",

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM