DEV Community

mktoho
mktoho

Posted on • Edited on

2

How to use authenticated proxy with Node's fetch

fetch in node

The fetch API is now available in node18. However, I was having trouble figuring out how to use a proxy.

Finally, we were able to use fetch through a proxy with the following code.

import { ProxyAgent, setGlobalDispatcher } from "undici"
import { Base64 } from "js-base64"

const agent = new ProxyAgent({
  uri: "http://yout-proxy-host:8080",
  auth: Base64.encode("username:password"),
})

setGlobalDispatcher(agent)

const main = async () => {
  const response = await fetch("https://api.example.com/super-cool-api")
  const json = await response.json()
  console.log(json)
}

main()
Enter fullscreen mode Exit fullscreen mode

I am not good at English so I leave you only with the successful code 🎮

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more